Jéjé
Jéjé

Reputation: 115

Parsing JSON result with Gson

I have an InputStreamReader reader that contains this JSON file: http://barcelonaapi.marcpous.com/bus/nearstation/latlon/41.3985182/2.1917991/1.json

Also, I have a class Station that contains ID, streetName, city, utmX, utmy, lat, lon as members.

What should i do, if I want parse the JSON file with GSon, to return an List<Station>?

I tried this :

gson.fromJson(reader, new TypeToken<List<Station>>(){}.getType());

But it raised an IllegalStateException (Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2).

How to extract only data which interests me (members of my Station class)?

Is it possible with GSon, or I need to use the JSON standard API provided by Android SDK (with JSONObject and JSONArray)?

Upvotes: 0

Views: 114

Answers (1)

MH.
MH.

Reputation: 45493

You're close, but in this case you can't directly map to a List<Station> because it is wrapped in json object (2 layers deep) that also contains some other fields. That's basically also what the error is trying to tell you: you're instructing Gson to map to an array/list of items (in json: [...]), but instead it encountered an object (in json: {...}).

The quickest solution is to create a POJO that reflects this json response. For example:

public class Response {
    @SerializedName("code") public int mCode;
    @SerializedName("data") public ResponseData mData;
}

public class ResponseData {
    @SerializedName("transport") public String mTransport;
    @SerializedName("nearstations") public List<Station> mStations;
}

Now you can map the json to the above Response and get the List<Station> from the result:

Response response = gson.fromJson(reader, Response.class);
List<Station> stations = response.mData.mStations;
// do something with stations...

If you like to do something a little more advanced, you can take a look into writing a custom deserialiser or type adapter.

Upvotes: 1

Related Questions