'How to update values in a complicated JSON Array using Jackson?
I have a request body (in JSON format) that looks like this:
[
{
"l_ts":0,
"af":{
"lib":"xyz",
"OS":"abc",
"wdt":"2.63",
},
"frs":false,
"g":"-v4d89ae6885b14baf91b102caaefea245",
"tlc":[],
"type":"meta",
},
{
"s":1643895073,
"evtName":"CONTENT_LIKE_DISLIKE",
"evtData":{
"contentId":17189,
"likeContent":true,
},
"type":"event",
"n":"_bg"
}
]
Now before sending the request, I need to update the value of "contentId" field. I am using Jackson in my current project, so what would be the best way to update the "contentId" field in the JSON above.
This is what I have tried till now:
ObjectMapper om = new ObjectMapper();
JsonNode requestBody = om.readTree(new File(pathToJsonAbove));
JsonNode requestBodyNode = requestBody.get(1);
requestBodyNode = JsonUtil.put(requestBodyNode, "evtData", "contentId", newValue);
requestBody = JsonUtil.put(requestBody, "[1]", requestBodyNode); // getting error here
The JsonUtil functions are as below:
public static final JsonNode put(JsonNode node, String key1, String key2, int value) {
JsonNode jsonNode = node.path(key1);
put(jsonNode, key2, value);
return node;
}
public static final JsonNode put(JsonNode node, String key, int value) {
return ((ObjectNode)node).put(key, value);
}
public static final JsonNode put(JsonNode node, String key, JsonNode value) {
return ((ObjectNode)node).putPOJO(key, value);
}
I am not able to successfully put the node that I have edited (requestBodyNode), back in the requestBody which is the main JsonNode that holds the entire body. When I run the above code, I get a ClassCastException saying that I can't convert from ArrayNode to ObjectNode.
What is the best way to update the "contentId" field in the JSON above?
Solution 1:[1]
If you have to update just the contentId field you can identify the parent node of the contentId node and modify the child (moreover basically you have already made more than that with the creation of your function throwing the error) :
ObjectMapper om = new ObjectMapper();
JsonNode requestBody = om.readTree(json);
JsonNode requestBodyNode = requestBody.get(1);
ObjectNode objectNode = (ObjectNode) requestBodyNode.get("evtData");
objectNode.put("contentId", 0); //<-- 0 chosen as the new value
//it will show contentId updated to 0
System.out.println(requestBody);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dariosicily |
