Sunday, August 9, 2015

Java: Store Json String into a Java Map


Following is the code to parse a json string and store the structure in Map
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

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


public class TestJson2{
 
 private static String jsonStr = "JSON String here";

 public static void main(String[] args){
  try{
   JSONObject obj = new JSONObject(jsonStr);
   parseJson(obj);
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public static void parseJson(JSONObject jsonObject){
  Map map = new LinkedHashMap();
  
  try{
   parseJson("", jsonObject, map);
   
   for(String key: map.keySet()){
    System.out.println(key + "::" + map.get(key));
   }
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public static Map parseJson(String key, JSONObject jsonObject, Map map){
  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), map);
      }
      else{
       map.put(keyVal, jsonArr.get(k));
      }
     }
    }
    else{
     if(jsonObject.get(obj) instanceof JSONObject){
      parseJson(keyVal, (JSONObject) jsonObject.get(obj), map);
     }
     else{
      map.put(keyVal, jsonObject.get(obj));
     }
    }
   }
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return map;
 }
}

No comments: