Sunday, August 9, 2015

Java: parse a JSON string


Following is the code to parse a json string
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class TestJson1{
 
 private static String jsonStr = "";

 public static void main(String[] args){
  try{
   JSONObject obj = new JSONObject(jsonStr);
   parseJson("", obj);
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public static void parseJson(String key, JSONObject jsonObject){
  try{
   Iterator iterator = jsonObject.keys();
   
   while(iterator.hasNext()){
    String obj = iterator.next().toString();
    String keyVal = (key.equals("")) ? obj : key + "." + obj;
    
    if(jsonObject.get(obj) instanceof JSONArray){
     JSONArray jsonArr = (JSONArray) jsonObject.get(obj);
     
     for(int k=0; k < jsonArr.length; k++){
      if(jsonArr.get(k) instanceof JSONObject){
       parseJson(keyVal + "[" + k + "]", (JSONObject) jsonArr.get(k));
      }
      else{
       System.out.println(keyVal + " :: " + jsonArr.get(k));
      }
     }
    }
    else{
     if(jsonObject.get(obj) instanceof JSONObject){
      parseJson(keyVal, (JSONObject) jsonObject.get(obj));
     }
     else{
      System.out.println(keyVal + " :: " + jsonObject.get(obj));
     }
    }
   }
   
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
}

No comments: