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

Viewed 25137

How do I iterate over a JSON response in Java using Jackson 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?

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