Search code examples
spring-bootresttemplateobjectmapper

restTemplate.getForObject doesn't read json array information


I'm in trouble to read a json data that have objects and arrays mixed in his body.

I can read and convert all objects kinds but the forecast node it is an array and I always receive an null as response.

See more details bellow:

My web API give me json response:

{
  "location": {
    "name": "Brasilia"

  },
  "current": {
    "last_updated": "2019-01-11 19:00",
    "condition": {
        "text": "Patchy rain possible"
    }
  },
  "forecast": {
    "forecastday": [
      {
        "date": "2019-01-11",
        "day": {
          "avgtemp_c": 21.4
        }
      },
      {
        "date": "2019-01-12",
        "day": {
          "avgtemp_c": 22.0
         }
      }
    ]
  }
}

I'm using restTemplate to get the data:

ApiResponse apiResponse = restTemplate.getForObject(uri, ApiResponse.class);

And here is my ApiResponse response estructure:

@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse {

    private Location location;
    private Current current; 
    private Forecast forecast;

    /*constructors, getters and setters mmited */
}   

@JsonIgnoreProperties(ignoreUnknown = true)
public class Location {

    private String name;    
    private String region;
    private String country;
    private Float lat;
    private Float lon;
    private String localtime;

    /*constructors, getters and setters mmited */
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Current {

    private String  last_updated;  
    private Float   temp_c;
    private Float   precip_mm;
    private Condition condition;

    /*constructors, getters and setters mmited */
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Forecast  {

    public List<Forecastday> forecastday;

    /*constructors, getters and setters mmited */
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Forecastday  {

    private String date; 
    private Day day;

    /*constructors, getters and setters mmited */
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Day {

    private Float  avgtemp_c;
    private Float totalprecip_mm;
    private List<Condition> condition;

    /*constructors, getters and setters mmited */
}

I guess that i am doing the class mapping in a wrong way but i can't see where is the problem.

Can any one help me?


Solution

  • Hey guys i've found the error.

    My mapping was really wrong!

    In my last class: private List<Condition> condition; isn't a list but a simple object: private Condition condition; and because this i was receiving a Cannot deserialize instance ofjava.util.ArrayListout of START_OBJECT token

    This another thread help me to see where i did wrong.