Gson not deserializing JSON data

713 Views Asked by At

I am trying to get some weather information from Yahoo APIs. This is my JSON:

JSON

This is my DTO:

public class forecast implements Serializable {

private static final long serialVersionUID = -520652416977871134L;
private String text;
private String high;
private String day;
private String code;
private String low;
private String date;

public forecast() {
}


public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getHigh() {
    return high;
}

public void setHigh(String high) {
    this.high = high;
}

public String getDay() {
    return day;
}

public void setDay(String day) {
    this.day = day;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getLow() {
    return low;
}

public void setLow(String low) {
    this.low = low;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

@Override
public String toString() {
    return "ClassPojo [text = " + text + ", high = " + high + ", day = "
            + day + ", code = " + code + ", low = " + low + ", date = "
            + date + "]";
}
}

I am only interested for the forecast element.

When I try to read the data de-serialized into my DTO all of them are null. I sense that I have not formatted my DTO properly.

Also, what Is the right way to map JSON to POJOs?

EDIT: this is my code for deserializing

    String endpoint = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20"
            + "where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Rhodes%2C%20Gr%22)&"
            + "format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    try {
        URL endpointURL = new URL(endpoint);
        HttpURLConnection connection = (HttpURLConnection) endpointURL
                .openConnection();
        connection.connect();
        InputStream input = connection.getInputStream();
        JsonReader reader = new JsonReader(new InputStreamReader(input));
        reader.setLenient(true);
        forecast response = new Gson().fromJson(reader,
                forecast.class);
        Log.d("forecast", response.toString());//override toString() to return all the values of the object
    } catch (IOException e) {
        e.printStackTrace();
    }
1

There are 1 best solutions below

4
On BEST ANSWER

Your JSON (which you get from Yahoo) is very complex. So it can not be easily mapped to simple POJO (but you still can write huge POJO that contains fields for all corresponding nested JSON elements).

But it is possible to parse and extract specific elements from JSON.

The code:

public static void main(String[] args) {
    String endpoint = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20"
            + "where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Rhodes%2C%20Gr%22)&"
            + "format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    try {
        URL endpointURL = new URL(endpoint);
        HttpURLConnection connection = (HttpURLConnection) endpointURL
                .openConnection();
        connection.connect();
        InputStream input = connection.getInputStream();
        JsonReader reader = new JsonReader(new InputStreamReader(input));
        reader.setLenient(true);

        JsonElement forecastSubObject = new JsonParser().parse(reader).
                getAsJsonObject().get("query").
                getAsJsonObject().get("results").
                getAsJsonObject().get("channel").
                getAsJsonObject().get("item").
                getAsJsonObject().get("forecast");  

        System.out.println(forecastSubObject.toString());   

        List<forecast> forecasts = (List<forecast>)new Gson().fromJson(forecastSubObject, List.class);

        System.out.println("forecast : " + forecasts);
        System.out.println("first forecast: " + forecasts.get(0));      
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Using JsonParser you can walk through elements (by theirs names). When 'forecast' element is reached corresponding string is extracted. Then it parsed as usual object and mapped to list of your forecast POJO.

Generally speaking mapping to/from JSON is very wide sphere. Different libraries provide different ways for achieving this (from simple and dirty to complex but reliable).