有没有办法使用 Jackson ObjectMapper 轻松更新 JSON 节点?
Is there a way to easily upade a JSON node using Jackson's ObjectMapper?
鉴于此 JSON 从文件中读取:
{
"Book": "Test",
"Subscription": [{
"RateIt": [{
"Id": "1234",
"Size": "XL",
"RateMe": [{
"id": "5678",
"Pages": ""
}],
"Test_Demo": null
}],
"DemoID": "test1111",
"subNumber": "9999"
}],
"Author_FirstName": "Test"
}
我尝试用不同的值更新 DemoID
字段,这样:
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
但是遇到异常:
java.lang.ClassCastException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
我也尝试使用 DemoIDpath,但遇到了同样的异常:
JsonNode idPath = requestParams.at("/Subscription/0/DemoID");//path was found OK
((ObjectNode) idPath).put("DemoID", "test0000"); // error on this line
我在使用 ObjectNode
时做错了什么?
Subscription
是一个数组。如果格式正确,您可能会看得更清楚:
{
"Book": "Test",
"Subscription": [
{
"RateIt": [
{
"Id": "1234",
"Size": "XL",
"RateMe": [
{
"id": "5678",
"Pages": ""
}
],
"Test_Demo": null
}
],
"DemoID": "test1111",
"subNumber": "9999"
}
],
"Author_FirstName": "Test"
}
将代码更改为:
((ObjectNode) subscriptionPath.get(0)).put("DemoID", "test0000");
鉴于此 JSON 从文件中读取:
{
"Book": "Test",
"Subscription": [{
"RateIt": [{
"Id": "1234",
"Size": "XL",
"RateMe": [{
"id": "5678",
"Pages": ""
}],
"Test_Demo": null
}],
"DemoID": "test1111",
"subNumber": "9999"
}],
"Author_FirstName": "Test"
}
我尝试用不同的值更新 DemoID
字段,这样:
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
但是遇到异常:
java.lang.ClassCastException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
我也尝试使用 DemoIDpath,但遇到了同样的异常:
JsonNode idPath = requestParams.at("/Subscription/0/DemoID");//path was found OK
((ObjectNode) idPath).put("DemoID", "test0000"); // error on this line
我在使用 ObjectNode
时做错了什么?
Subscription
是一个数组。如果格式正确,您可能会看得更清楚:
{
"Book": "Test",
"Subscription": [
{
"RateIt": [
{
"Id": "1234",
"Size": "XL",
"RateMe": [
{
"id": "5678",
"Pages": ""
}
],
"Test_Demo": null
}
],
"DemoID": "test1111",
"subNumber": "9999"
}
],
"Author_FirstName": "Test"
}
将代码更改为:
((ObjectNode) subscriptionPath.get(0)).put("DemoID", "test0000");