我希望按键存储和访问嵌套的json值,例如 arrayOfObjectList.objectKey1 objectKey.objectKey1 ,其他。现在我将数据存储在 HashMap(String,Object )中,我不知道如何通过密钥访问它 因为json有不确定的层,内部数据可以是arrayList,object和string。请介绍我完成这项任务。
我是初学者,对不起我的算法
码
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());
}
方法
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数据
{
"stringKey": "stringValue",
"valueStringList": [
"value1",
"value2"
],
"arrayOfObjectList": [
{
"objectKey1": "objectValue1",
"objectKey2": "objectValue2"
},
{
"objectKey1": "objectValue1",
"objectKey2": "objectValue2"
}
],
"objectKey": {
"objectKey1": "objectValue1",
"objectKey2": "objectValue2"
}
}