How to repeat JSON response using Jackson API (list inside list)?

How to do a JSON response repetition in Java using the Jackson API? In other words, if there is a list in the answer, and inside this list there is another list (in this case it is called "weather"), then how can I get the temperature ?

Here is an example of what I'm trying to accomplish 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'm trying to use that does not work, because I can only iterate over the first element:

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("-----------------");
+4
source share
3 answers

You parse JSON when Jackson has to do it for you. Do not do this with yourself.

DTO (Data Transfer Object), JSON

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
+6

, 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();
}
+1

. , 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;
}
0

All Articles