0

I want store and access nested json value by key such as arrayOfObjectList.objectKey1 objectKey.objectKey1 and others. Now I store data in HashMap(String,Object) and I don't know how to access it by key because json has indeterminate layer and inner data can be arrayList, object and string. Please introduce me to accomplish this task.

I am a beginner, sorry for my algorithm

code

   Gson gson = new Gson();
   HashMap<String,Object> param = new HashMap<>();
   param = (HashMap<String, Object>) gson.fromJson(jsonData, param.getClass());
    for (Map.Entry resourceItem : param.entrySet()) {
        checkAndParseInternalLayer(param,resourceItem.getKey().toString());
    }

method

    void checkAndParseInternalLayer(HashMap<String, Object> data, String key) {
    Object obj = data.get(key);

    if (obj instanceof ArrayList) {
        List<Object> internalList = new ArrayList<>();
        for (Object dataObj : (ArrayList)obj) {
            if (dataObj instanceof LinkedTreeMap) {
                // get all key in LinkedTreeMap
                Set<String> keySet = ((LinkedTreeMap) dataObj).keySet();
                HashMap<String, Object> internalMap = new HashMap<>();

                // set HashMap
                for (String keyStr : keySet) {
                    AFLog.d("set map : "+keyStr+" = "+((LinkedTreeMap) dataObj).get(key));
                    internalMap.put(keyStr, ((LinkedTreeMap) dataObj).get(keyStr));
                }

                // check internal layer
                for (HashMap.Entry entry : internalMap.entrySet()) {
                    checkAndParseInternalLayer(internalMap, entry.getKey().toString());
                }
                internalList.add(internalMap);
            }
            else if (dataObj instanceof String) {
                internalList.add(dataObj);
            }
        }
        data.put(key, internalList);
    } else if (obj instanceof LinkedTreeMap) {
        // get all key in LinkedTreeMap
        Set<String> keySet = ((LinkedTreeMap) obj).keySet();
        HashMap<String, Object> internalMap = new HashMap<>();

        // set HashMap
        for (String keyStr : keySet) {
            internalMap.put(keyStr, ((LinkedTreeMap) obj).get(keyStr));
        }

        // check internal layer
        for (HashMap.Entry entry : internalMap.entrySet()) {
            checkAndParseInternalLayer(internalMap, entry.getKey().toString());
        }
        data.put(key, internalMap);
    }
}

json data

    {
      "stringKey": "stringValue",
      "valueStringList": [
         "value1",
         "value2"
      ],
      "arrayOfObjectList": [
       {
         "objectKey1": "objectValue1",
         "objectKey2": "objectValue2"
       },
       {
         "objectKey1": "objectValue1",
         "objectKey2": "objectValue2"
       }
      ],
      "objectKey": {
        "objectKey1": "objectValue1",
        "objectKey2": "objectValue2"
      }
    }

0 Answers0