Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java JSON Parser: Recursively parse any JSON and print the output.
package preiss;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
public static void main(String[] args) {
String json = "{"+
"\"access_codes_count\": 1,"+
"\"access_codes\": ["+
"{"+
"\"user_id\":\"132456789\","+
"\"recorded_at\":\"2015-06-21 11:11:36 +0200\","+
"\"subscription_awarded\" : true,"+
"\"access_id\" : 8856722394824735,"+
"\"subscription\": {"+
"\"valid_from\":\"2015-06-24 11:11:37 +0200\","+
"\"terminated_at\":null,"+
"\"suspended\":false,"+
"\"subscription_type\":\"premium\""+
"}"+
"},"+
"{"+
"\"user_id\":\"132456789\","+
"\"recorded_at\":\"2015-06-21 11:11:36 +0200\","+
"\"subscription_awarded\" : true,"+
"\"access_id\" : 8856722394824735,"+
"\"subscription\": {"+
"\"valid_from\":\"2015-06-24 11:11:37 +0200\","+
"\"terminated_at\":null,"+
"\"suspended\":false,"+
"\"subscription_type\":\"premium\""+
"}"+
"}"+
"]"+
"}";
JSONParser jp = new JSONParser();
jp.parse(json);
}
public void parse(String json) {
try{
JSONObject jsonObj = new JSONObject(json);
parse("","",jsonObj,0);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public void parse(String grandParentKey, String parentKey, JSONObject json, int count) throws JSONException {
@SuppressWarnings("unchecked")
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
Object val = null;
val = json.get(key);
if (val.getClass().getTypeName().contains("JSONArray")){
JSONArray jArr = (JSONArray) val;
for(int i=0; i<jArr.length(); i++){
count++;
JSONObject childJSONObject = jArr.getJSONObject(i);
parse(parentKey, key, childJSONObject, count);
}
}else if (val.getClass().getTypeName().equals("org.json.JSONObject")){
parse(parentKey, key, (JSONObject) val, count);
}else{
if (val.getClass().getTypeName().toString().equals("org.json.JSONObject$Null")){
val="null";
}
if (val != null) {
String s1 ="";
if(!grandParentKey.isEmpty()){
s1 = grandParentKey + count +"."+ parentKey + "." + key;
}else if (!parentKey.isEmpty()){
s1 = parentKey +count+ "." + key;
} else {
s1 = key;
}
System.out.println("KEY: " + s1);
System.out.println("VALUE: " + val.toString());
System.out.println("-----");
}
}
}
}//End Method
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.