Given this JSON read from a file:
{
"Book": "Test",
"Subscription": [{
"RateIt": [{
"Id": "1234",
"Size": "XL",
"RateMe": [{
"id": "5678",
"Pages": ""
}],
"Test_Demo": null
}],
"DemoID": "test1111",
"subNumber": "9999"
}],
"Author_FirstName": "Test"
}
I tried to update DemoID
field with a different value, this way:
ObjectMapper mapper = new ObjectMapper();
JsonNode requestParams = mapper.readTree(new File("src/test/resources/myFile.json"));
JsonNode subscriptionPath = requestParams.at("/Subscription");
System.out.println(subscriptionPath ); //value was retrieved OK
((ObjectNode) subscriptionPath).put("DemoID", "test0000"); //error on this line
But got the exception:
java.lang.ClassCastException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
I also tried using the DemoIDpath instead, but got the same exception:
JsonNode idPath = requestParams.at("/Subscription/0/DemoID");//path was found OK
((ObjectNode) idPath).put("DemoID", "test0000"); // error on this line
What am I doing wrong with the use of ObjectNode
?
CodePudding user response:
Subscription
is an array. You may see it better with proper formatting:
{
"Book": "Test",
"Subscription": [
{
"RateIt": [
{
"Id": "1234",
"Size": "XL",
"RateMe": [
{
"id": "5678",
"Pages": ""
}
],
"Test_Demo": null
}
],
"DemoID": "test1111",
"subNumber": "9999"
}
],
"Author_FirstName": "Test"
}
Change code to:
((ObjectNode) subscriptionPath.get(0)).put("DemoID", "test0000");