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

时间:2013-12-30 01:14:27

标签: json jackson

如何使用Jackson API在Java中迭代JSON响应?换句话说,如果响应有一个列表,并且该列表中有另一个列表(在本例中称为'weather'),那么如何获得温度

以下是我尝试迭代的示例:

{
   "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
            }
         ]
      }
   ]
}

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

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("-----------------");

3 个答案:

答案 0 :(得分:11)

当杰克逊打算为你做这件事时,你正在解析JSON。不要对自己这样做。

一种选择是创建与您的JSON格式相匹配的DTO(Data Transfer Object

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
}

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

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

然后,您可以获得所需的字段。例如

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

打印

74

另一种方法是将您的JSON作为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());

还打印

74

答案 1 :(得分:2)

根据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();
}

答案 2 :(得分:0)

我知道它已经过时了。如果您需要将JSON转换为列表并且您的对象中没有直接设置器,那么这是我的解决方案 假设你有'玩家'的JSON结构:

<强> JSON:

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

<强> 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:

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;
}