简体   繁体   English

用Gson解析JSON结果

[英]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 我有一个包含以下JSON文件的InputStreamReader readerhttp : //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. 另外,我有一个Station类,其中包含ID, streetName, city, utmX, utmy, lat, lon作为成员。

What should i do, if I want parse the JSON file with GSon, to return an List<Station> ? 如果我想用GSon解析JSON文件,该怎么办,以返回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) . 但是它引发了一个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)? 如何只提取我感兴趣的数据( Station类的成员)?

Is it possible with GSon, or I need to use the JSON standard API provided by Android SDK (with JSONObject and JSONArray )? GSon是否可能,或者我需要使用Android SDK提供的JSON标准API(带有JSONObjectJSONArray )?

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. 您已经接近了,但是在这种情况下,您不能直接映射到List<Station>因为它包装在还包含一些其他字段的json对象(深2层)中。 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: {...} ). 这基本上也是错误试图告诉您的内容:您正在指示Gson映射到项的数组/列表(在json: [...] ),但是却遇到了一个对象(在json: {...} )。

The quickest solution is to create a POJO that reflects this json response. 最快的解决方案是创建一个反映此json响应的POJO。 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: 现在,您可以将json映射到上面的Response并从结果中获取List<Station>

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 . 如果您想做一些更高级的事情,可以看一下编写自定义反序列化器或类型适配器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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