Alej
Alej

Reputation: 13

How can I keep GSON from returning null when parsing a basic JSON object?

I'm working on a basic JSON problem: I take a JSON formatted string (from http://api.open-notify.org/iss-now.json). I pass it into a method that attempts to parse the information into a class called ISSClass so that I can read the fields of longitude and latitude.

When I try to return the two fields they are null.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
public class GetWeather 
{
    public String getISSInfo(String json)
    {
        String output="";
        Gson gson=new   GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        ISSClass cond=new ISSClass();
        cond= gson.fromJson(json, ISSClass.class);
        output+="The ISS is at: "+cond.toString();
        return output;
    }
    class ISSClass
    {
        public ISSClass(){}

        @Expose
        public String latitude;
        @Expose
        public String longitude;

        public String toString()
        {
            return latitude+", "+longitude;
        }
        public void setLongitude(String lon)
        {
            longitude=lon;
        }
        public void setLatitude(String lat)
        {
            latitude=lat;
        }
        public String getLongitude()
        {
            return longitude;
        }
        public String getLatitude()
        {
            return latitude;
        }
    }
}

And here's the main:

public class GsonTester 
{
    public static void main(String[] args) throws Exception
    {
        JsonReader reader=new JsonReader();
        String toParse="{\"message\": \"success\", \"timestamp\": 1501887780, \"iss_position\": {\"latitude\": \"-35.5370\", \"longitude\": \"-178.7080\"}}";
        GetWeather weather=new GetWeather();
        System.out.println(weather.getISSInfo(toParse));
    }
}

I've tried using @SerializedName("longitude") with no luck. Same with instantiating 'gson' as Gson gson=new Gson(); I'm using gson-2.8.1.jar for gson.

Hope I'm missing something obvious.

Upvotes: 1

Views: 1263

Answers (1)

mgyongyosi
mgyongyosi

Reputation: 2667

It doesn't work because the longitude and latitude are in iss_position nested object and the unmarshaller tries to resolve the fields from the top level.

The easiest way to solve it to create a JsonParser and extract the nested field value (iss_position) and unmarshall it.

public String getISSInfo(String json) {
    String output = "";
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

    JsonParser parser = new JsonParser();
    JsonObject top = parser.parse(json).getAsJsonObject();
    String nested = top.get("iss_position").toString();
    ISSClass cond = gson.fromJson(nested, ISSClass.class);

    output += "The ISS is at: " + cond.toString();
    return output;
}

Upvotes: 1

Related Questions