Skip to content

Instantly share code, notes, and snippets.

@lizettepreiss
Last active October 30, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizettepreiss/cb875fee745750b990e2171f1638aa3d to your computer and use it in GitHub Desktop.
Save lizettepreiss/cb875fee745750b990e2171f1638aa3d to your computer and use it in GitHub Desktop.
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