简体   繁体   English

如何在主 class - JSON 中获取嵌套数组值到 POJO

[英]How to get nested array values in main class - JSON to POJO

I have a JSON like this:我有一个像这样的 JSON:

{
   "types":[
      {
         "slot":1,
         "type":{
            "name":"grass",
            "url":"https://pokeapi.co/api/v2/type/12/"
         }
      },
      {
         "slot":2,
         "type":{
            "name":"poison",
            "url":"https://pokeapi.co/api/v2/type/4/"
         }
      }
   ]
}

I need only names of types, so I'd like to have something like this:我只需要类型的名称,所以我想要这样的东西:

public class MainClass {

    private List<String> types;
}

I want to avoid creating of nested classes.我想避免创建嵌套类。 How can I get this result?我怎样才能得到这个结果?

The simplest way is to convert your JSON to map and retrieve from there the List and from each element get Map and get the value by key type.最简单的方法是将 JSON 转换为 map 并从那里检索 List 并从每个元素中获取 Map 并通过键类型获取值。 Here is the link to a question on how to parse your JSON .这是有关如何解析 JSON 的问题的链接 The rest should be trivial rest 应该是微不足道的

Using Jackson, you can do:使用 Jackson,您可以:

ArrayNode types = objectMapper.readTree(jsonStr).withArray("types");

List<String> typeNames = IntStream.range(0, types.size())
        .mapToObj(types::get)
        .map(json -> json.get("type")
            .get("name")
            .asText())
        .collect(Collectors.toList());

or using org.json , you can do:或使用org.json ,你可以这样做:

JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("types");

List<String> typeNames = IntStream.range(0, jsonArray.length())
        .mapToObj(jsonArray::getJSONObject)
        .map(json -> json.getJSONObject("type")
                .getString("name"))
        .collect(Collectors.toList());

Both return the output:两者都返回 output:

[grass, poison]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM