Statement:
Because the names in the hierarchical json objects may be duplicate, the key value is accompanied by the parent key in all flattening
Use a list of keys to determine whether there are duplicate key inserts. If the key already exists, skip.
If the information of each field is indispensable, it can be judged that there are duplicate keys. If you change the key value name, you can get the insertion value normally.
/**
* Processing jsonNode recursively
* @param map Form object to return
* @param parentPath Father path
* @param parentJsonNode Parent node object
*/
private void setNodePath(Map<String, Object> map, String parentPath, JsonNode parentJsonNode) {
Iterator<String> sIterator = parentJsonNode.fieldNames();
while(sIterator.hasNext()) {
String key = sIterator.next();
JsonNode jsonNode = parentJsonNode.get(key);
if(jsonNode.isArray()) {
for (int i = 0; i < jsonNode.size(); i++) {
if (null != jsonNode.get(0)) {
Iterator<String> grid = jsonNode.get(0).fieldNames();
while(grid.hasNext()) {
String child = grid.next();
JsonNode jn = jsonNode.get(0).get(child);
String mapKey = key + "." + child;
if (jn.isDouble()) {
if (map.containsKey(mapKey)) {
map.put(mapKey, (Double)(map.get(mapKey)) + jn.asDouble());
} else {
map.put(mapKey, jn.asDouble());
}
} else if (jn.isFloat()) {
if (map.containsKey(mapKey)) {
map.put(mapKey, (Float)(map.get(mapKey)) + jn.asDouble());
} else {
map.put(mapKey, jn.asDouble());
}
} else if (jn.isInt()) {
if (map.containsKey(mapKey)) {
map.put(mapKey, (Integer)(map.get(mapKey)) + jn.asInt());
} else {
map.put(mapKey, jn.asInt());
}
} else {
if (map.containsKey(mapKey)) {
map.put(mapKey, (String)(map.get(mapKey)) + "," + jn.asText());
} else {
map.put(mapKey, jn.asText());
}
}
}
}
}
map.put(key, jsonNode.toString());
}
else if(jsonNode.isValueNode()) {
map.put(parentPath + "." + key, jsonNode.asText());
}
else if(jsonNode.isObject()) {
setNodePath(map, parentPath + "." + key, jsonNode);
}
}
}