本文介绍了如何使用jackson遍历生成的json模式并将自定义属性放在json模式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "i": {
      "type": "integer"
    },
    "p": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "i": {
          "type": "integer"
        },
        "p1": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "id": {
              "type": "string"
            },
            "i": {
              "type": "integer"
            }
          }
        }
      }
    }
  },
  "classname": "com.tibco.tea.agent.Person"
}

我有上面生成的模式,我想对其进行一些修改。如您所见,我在此架构中嵌套了Object。我想为每个对象插入一个classname属性。任何人都可以建议我如何使用jackson 2.3.0遍历此模式并按上述方式操作它。

I've the above generated schema, to which I want to do some modification. As you can see, I've nested Object's in this schema. I want to insert a "classname" attribute for each object. Can anybody suggest me how can I use jackson 2.3.0 to traverse through this schema and manipulate it as mentioned above.

推荐答案

如果节点是对象,您可以将它们转换为 ObjectNode 并使用 put 方法添加所需的键/值对。

If the nodes are objects, You could cast them to an ObjectNode and use the put method to add desired key/value pairs.

JSON = // stuff you have in example
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(JSON);
// using root node for this example
if (jsonNode.isObject()) {
    ((ObjectNode) jsonNode).put("classname", "com.stackoverflow.Cheese");
}

这篇关于如何使用jackson遍历生成的json模式并将自定义属性放在json模式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:49