如何使用 Jackson API(列表中的列表)迭代 JSON 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20832015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:08:39  来源:igfitidea点击:

How do I iterate over a JSON response using Hymanson API (of a List inside a List)?

jsonHymanson

提问by djangofan

How do I iterate over a JSON response in Java using Hymanson API? In other words, if the response has a list and inside that list is another list ( in this case called 'weather') , then how do I get the temperature?

如何使用 Hymanson API 在 Java 中迭代 JSON 响应?换句话说,如果响应有一个列表,并且该列表内有另一个列表(在这种情况下称为“天气”),那么我如何获得温度

Here is an example of what I am trying to iterate through:

这是我尝试迭代的示例:

{
   "message":"like",
   "cod":"200",
   "count":3,
   "list":[
      {
         "id":2950159,
         "name":"Berlin",
         "coord":{
            "lon":13.41053,
            "lat":52.524368
         },
         "weather":[
            {
               "id":804,
               "main":"Clouds",
               "description":"overcast clouds",
               "temp":74
            }
         ]
      },
      {
         "id":2855598,
         "name":"Berlin Pankow",
         "coord":{
            "lon":13.40186,
            "lat":52.56926
         },
         "weather":[
            {
               "id":804,
               "main":"Clouds",
               "description":"overcast clouds",
               "temp":64
            }
         ]
      }
   ]
}

And here is the code I am trying to use, which doesn't work, because I can only iterate through the first item:

这是我尝试使用的代码,它不起作用,因为我只能遍历第一项:

try {                
    JsonFactory jfactory = new JsonFactory();
    JsonParser jParser = jfactory.createJsonParser( new File("test.json") );

    // loop until token equal to "}"
    while ( jParser.nextToken() != JsonToken.END_OBJECT ) {

        String fieldname = jParser.getCurrentName();

        if ( "list".equals( fieldname ) ) { // current token is a list starting with "[", move next                 
        jParser.nextToken();                                  
        while ( jParser.nextToken() != JsonToken.END_ARRAY ) {
            String subfieldname = jParser.getCurrentName();
            System.out.println("- " + subfieldname + " -");
            if ( "name".equals( subfieldname ) ) {
                jParser.nextToken();
                System.out.println( "City: " + jParser.getText() );                         }        
            }            
        }

        }
        jParser.close();

        } catch (JsonGenerationException e) {        
            e.printStackTrace();         
        } catch (JsonMappingException e) {       
         e.printStackTrace();        
        } catch (IOException e) {        
         e.printStackTrace();        
        }
        System.out.println("-----------------");

回答by Sotirios Delimanolis

You are parsing the JSON when Hymanson is meant to do it for you. Don't do this to yourself.

当Hyman逊打算为您解析时,您正在解析 JSON。不要对自己这样做。

One option is to create a DTO (Data Transfer Object) that matches the format of your JSON

一种选择是创建与 JSON 格式匹配的DTO(数据传输对象

class Root {
    private String message;
    private String cod;
    private int count;
    private List<City> list;
    // appropriately named getters and setters
}

class City {
    private long id;
    private String name;
    private Coordinates coord;
    private List<Weather> weather;
    // appropriately named getters and setters
}

class Coordinates {
    private double lon;
    private double lat;
    // appropriately named getters and setters
}

class Weather {
    private int id;
    private String main;
    private String description;
    private int temp;
    // appropriately named getters and setters
}

Then use an ObjectMapperand deserialize the root of the JSON.

然后使用 anObjectMapper并反序列化 JSON 的根。

ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(yourFileInputStream, Root.class);

You can then get the field you want. For example

然后你可以得到你想要的字段。例如

System.out.println(root.getList().get(0).getWeather().get(0).getTemp());

prints

印刷

74

The alternative is to read your JSON in as a JsonNodeand traverse it until you get the JSON element you want. For example

另一种方法是将您的 JSON 作为 a 读取JsonNode并遍历它,直到您获得所需的 JSON 元素。例如

JsonNode node = mapper.readTree(new File("text.json"));
System.out.println(node.get("list").get(0).get("weather").get(0).get("temp").asText());

also prints

也打印

74

回答by djangofan

Based on the answer that Sotirios Delimanolis gave me, here was my solution:

根据 Sotirios Delimanolis 给我的答案,这是我的解决方案:

ObjectMapper mapper = new ObjectMapper();
JsonFactory jfactory = mapper.getFactory();
JsonParser jParser;
try {
    jParser = jfactory.createParser( tFile );
    JsonNode node = mapper.readTree( jParser);
    int count = node.get("count").asInt();
    for ( int i = 0; i < count; i++ ) {
     System.out.print( "City: " + node.get("list").get(i).get("name").asText() );
        System.out.println( " , Absolute temperature: " + 
            node.get("list").get(i).get("main").get("temp").asText() );
    }
    jParser.close();
} catch (IOException e) {
    e.printStackTrace();
}

回答by IgorZ

I know it's old. This is my solution if you need to convert a JSON into a list and you don't have direct setters in your object.
Let's say that you have this JSON structure of 'Players':

我知道它很旧了。如果您需要将 JSON 转换为列表并且您的对象中没有直接的 setter,这是我的解决方案。
假设您有这个“玩家”的 JSON 结构:

JSON:

JSON:

{
  "Players":
           [
             {
               "uid": 1, "name": "Mike",
               "stats": {"shots" : 10, "hits": 5}
             },
             {
               "uid": 2, "name": "John",
               "stats": {"shots": 4, "hits": 1}
             }
           ]
}

getListOfPlayersFromJson:

getListOfPlayersFromJson:

public static List<Player> getListOfPlayersFromJson(String json) {
    List<Player> players = new ArrayList<>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(json);
        root.at("/Players").forEach(node -> {
            Player p = getPlayerFromNode(node);
            players.add(p);
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return players;
}

getPlayerFromNode:

getPlayerFromNode:

public static Player getPlayerFromNode(JsonNode node) {
    Player player = new Player();
    player.setUid(node.at("/uid").longValue());
    player.setName(node.at("/name").asText());
    player.setStats(
            node.at("/stats/shots").asInt(),
            node.at("/stats/hits").asInt()
    );
    return player;
}