【问题标题】:get field list from json object list with Jackson使用 Jackson 从 json 对象列表中获取字段列表
【发布时间】:2018-12-23 05:04:07
【问题描述】:

我有从 api 获取的 JSON 数据,我想获取 json 数据中的字段列表。

JSON 数据:

    [  
       {  
          "code":"en",
          "native":true,
          "plurals":{  
             "length":2,
             "forms":[  
                "one",
                "other"
             ]
          }
       }, {  
          "code":"de",
          "native":true,
          "plurals":{  
             "length":2,
             "forms":[  
                "one",
                "other"
             ]
          }
       }, {  
          "code":"le",
          "native":true,
          "plurals":{  
             "length":2,
             "forms":[  
                "one",
                "other"
             ]
          }
       }
]

我想获取代码字段数据为list<String>,如下所示:

["en","de","le"]

最简单的方法是什么?

注意:我正在使用 Spring 的 RestTemplate 来获取数据。

【问题讨论】:

  • 你有 dto 类吗?
  • @CodeIsLife 不,我需要吗?
  • @CodeIsLife 如果我需要我可以创建一个

标签: json parsing spring-boot jackson resttemplate


【解决方案1】:

使用findValues方法提取所有名为“code”的属性的值:

ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree(json);

List<JsonNode> code = tree.findValues("code");

在您的示例数据上运行它会得到结果

["en", "de", "le"]

【讨论】:

    【解决方案2】:

    试试下面的方法。

    public static void main(String[] args) throws JSONException {
            String jsonString  = jsonResponseFromApi;
    
            JSONObject obj= new JSONObject();
            JSONObject jsonObject = obj.fromObject(jsonString);
    
            ArrayList<String> list = new ArrayList<String>();
    
            for(int i=0; i<jsonObject.length(); i++){
                list.add(jsonObject.getJSONObject(i).getString("code"));
            }
    
            System.out.println(list);
        }   
        }
    

    更多详情请参阅下面的帖子How to Parse this JSON Response in JAVA

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多