Generic JSON Object Parsing or Unknwon JSON Object parsing using Gson librarry


public class JsonParsing {

    static JsonParser parser = new JsonParser();
    public static HashMap<String, Object> createHashMapFromJsonString(String json) {

        JsonObject object = (JsonObject) parser.parse(json);        
        Set<Map.Entry<String, JsonElement>> set = object.entrySet();        
        Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();        
        HashMap<String, Object> map = new HashMap<String, Object>();
        while (iterator.hasNext()) {

            Map.Entry<String, JsonElement> entry = iterator.next();            
            String key = entry.getKey();            
            JsonElement value = entry.getValue();
            if (null != value) {
                if (!value.isJsonPrimitive()) {
                    if (value.isJsonObject()) {

                        map.put(key, createHashMapFromJsonString(value.toString()));                    
                     } else if (value.isJsonArray() && value.toString().contains(":")) {

                        List<HashMap<String, Object>> list = new ArrayList<>();                        
                        JsonArray array = value.getAsJsonArray();                        
                        if (null != array) {
                            for (JsonElement element : array) {
                                list.add(createHashMapFromJsonString(element.toString()));                            
                        }
                            map.put(key, list);                        }
                    } else if (value.isJsonArray() && !value.toString().contains(":")) {
                        map.put(key, value.getAsJsonArray());                    }
                } else {
                    map.put(key, value.getAsString());                }
            }
        }
        return map;    }
}

Comments

  1. Using Gson Librarry:

    String jsonString = "Your JSON string";
    HashMap map = new Gson().fromJson(jsonString, new TypeToken>(){}.getType());

    ReplyDelete

Post a Comment

Popular posts from this blog

Working with Android Hierarchy Viewer

Android: Standalone login with SQLiteOpenHelper