简体   繁体   中英

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 )?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM