我有一个InputStreamReader reader
包含此 JSON 文件:
http://barcelonaapi.marcpous.com/bus/nearstation/latlon/41.3985182/2.1917991/1.json
另外,我有一个类(class)Station
其中包含 ID, streetName, city, utmX, utmy, lat, lon
作为成员(member)。
如果我想用 GSon 解析 JSON 文件,我应该做什么,以返回 List<Station>
?
我尝试过这个:
gson.fromJson(reader, new TypeToken<List<Station>>(){}.getType());
但它提出了 IllegalStateException (Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2)
.
如何仅提取我感兴趣的数据(我的 Station
类的成员)?
GSon 是否可以,或者我需要使用 Android SDK 提供的 JSON 标准 API(使用 JSONObject
和 JSONArray
)?
最佳答案
您已经很接近了,但在这种情况下您无法直接映射到 List<Station>
因为它被包装在 json 对象(2 层深)中,该对象还包含一些其他字段。这基本上也是错误试图告诉您的内容:您指示 Gson 映射到项目数组/列表(在 json 中: [...]
),但它遇到了一个对象(在 json 中: {...}
)。
最快的解决方案是创建一个反射(reflect)此 json 响应的 POJO。例如:
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;
}
现在你可以将json映射到上面的Response
并获取List<Station>
从结果来看:
Response response = gson.fromJson(reader, Response.class);
List<Station> stations = response.mData.mStations;
// do something with stations...
如果你想做一些更高级的事情,你可以看看写一个 custom deserialiser or type adapter .
关于java - 使用Gson解析JSON结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33309834/