[英]How to convert a nested jsonObject to a hashMap with updated field names in java with Jackson?
UPDATE
: updated the codebase and now I am getting the key values pairs but there is some issue with the recursion logic while adding key|value pair. UPDATE
:更新了代码库,现在我得到了键值对,但是在添加键|值对时递归逻辑存在一些问题。 Need help with fixing this code.需要帮助修复此代码。 OLD ISSUE
:I have been trying to convert a JSON
into a HashMap
but as the JSON
is a nested object I am unable to save the key name for the nested fields during recursion calls. OLD ISSUE
:我一直在尝试将JSON
转换为HashMap
但由于JSON
是嵌套对象,因此我无法在递归调用期间保存嵌套字段的键名。 Below is the updated sample code:以下是更新后的示例代码:
private HashMap<String,Object> addToMap(JsonNode jsonNode, HashMap<String, Object> map) {
// TODO Auto-generated method stub
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
parentKey=entry.getKey();
//set key from the mapperLookup.
map.put(parentKey, addToMap(entry.getValue(),new HashMap<String,Object>()));
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
//set key from the mapperLookup.
map.put(parentKey, addToMap(arrayNode.get(i),new HashMap<String,Object>()));
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
//set key from the mapperLookup.
map.put(parentKey, valueNode.asText());
}
return map;
}
Sample input:样本输入:
{
"S_name":"xyz",
"K_id":"12233",
"N_dum":[{"K_id":"dfff"},{"S_nam":"dfgg"}]
}
expected output:预期输出:
{S_name=xyz,
K_id=12233,
N_dum={K_id=dfff,S_nam=dfgg}
}
Current output:电流输出:
{S_name={S_name=xyz}, K_id={K_id=12233}, N_dum={N_dum={K_id={K_id=dfff}}, K_id={S_nam={S_nam=dfgg}}}}
Improvements would be helpful.改进会有所帮助。 As I need to do some transformation with the key names that's why I am following this approach.因为我需要对键名进行一些转换,这就是我遵循这种方法的原因。
You can try using ObjectMapper like following:您可以尝试使用 ObjectMapper,如下所示:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> dataRaw = null;
dataRaw = mapper.readValue(rawValues, new TypeReference<Map<String, Object>>() {});
which rawValues is a json string.其中 rawValues 是一个 json 字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.