首页 > 解决方案 > 导航到特定的 JSON 节点并使用 ObjectMapper

问题描述

我想使用 Jackson 导航到特定的 JSON,然后通过 ObjectMapper 发送值。如果 JSON 只是一个像这样的简单数组,我目前可以实现这一点:

[
    {
        "parent": "A",
        "child": "B"
    },{
        "parent": "G",
        "child": "K"
    }
]

我的 Java 代码看起来像这样,它可以工作。

ObjectMapper mapper = new ObjectMapper();
Row[] row;

row = mapper.readValue(json, Row[].class);

但是当 JSON 像这样嵌套更多时:

{
    "data": [
        {
            "parent": "A",
            "child": "B"
        },{
            "parent": "G",
            "child": "K"
        }
    ]
}

我不确定我需要做什么才能达到同样的效果。

该类Row只是一个标准类,具有 parent 和 child 属性以及它的 getter 和 setter。那里没什么特别的。

标签: javajackson

解决方案


你应该使用地图。其中数据是映射中的键,对象列表是值。这是您的列表 [] 是值。在您的列表中,您有一个对象。在 java 中...

     Map<String, List<Parents>> studentsParent = HashMap<>(); class Parent{ String parent; String child; parent(String parent, String child){
         this.parent = parent;
         this.child = child; } 
} List<Parents> parents = new ArrayList<>(); 
  studentsParent.put (data, Parents.add( Parent p = new Parent("A", "B"))); [
            {
                "parent": "A",
                "child": "B"
            },{
                "parent": "G",
                "child": "K"
            }
        ]

推荐阅读