我正在使用com.fasterxml.jackson.databind.JsonNode
java 库来解析 aJSON
并对JSON
字符串执行一些操作,如下所示 -
public static void main(String[] args) {
{
String jsonString = "{\"state\":{\"reported\":{\"deviceParams\":{\"deviceStatus\":{\"solenoid\":10,\"airFlow\":20}}}}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
JsonNode subNode = jsonNode.get("state").get("reported").get("deviceParams").get("deviceStatus");
//Now subNode = {"solenoid":10,"airFlow":20}
modifySubNode((ObjectNode) subNode);
//type-casting JsonNode to ObjectNode since JSON manipulation like deletion and addition of nodes is only allowed in ObjectNode, not JsonNode
}
private static void modifySubNode(ObjectNode node) {
if (node.get("solenoid") != null) {
node.put("solenoid", 100);
}
}
在函数调用之后modifySubNode()
,我希望 的值jsonNode
保持为
{
"state":
{
"reported":
{
"deviceParams":
{
"deviceStatus":
{
"solenoid": 10,
"airFlow": 20
}
}
}
}
}
但相反,它变成了这个
{
"state":
{
"reported":
{
"deviceParams":
{
"deviceStatus":
{
"solenoid": 100,
"airFlow": 20
}
}
}
}
}
为什么会这样?我认为对“子节点”的任何更改都不应该反映在“ jsonNode
”上。是不是我的理解有误?