【发布时间】:2019-05-08 23:18:50
【问题描述】:
我在尝试将此 JSON 响应解析为 "properties" 元素列表时遇到了困难。我的 JSON 如下所示:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"mag": 6.6,
"place": "192km ESE of Tadine, New Caledonia"
}
},
{
"type": "Feature",
"properties": {
"mag": 7.5,
"place": "168km ESE of Tadine, New Caledonia"
}
},
{
"type": "Feature",
"properties": {
"mag": 6,
"place": "155km ESE of Tadine, New Caledonia"
}
}
]
}
这是包含地震详细信息的响应,所以基本上"features" 中的每个"properties" 都是我想要的 POJO,但它们都只是在一个列表中。这是我的Earthquake 课程:
public class Earthquake {
@SerializedName("mag")
private double magnitude;
@SerializedName("place")
private String location;
public Earthquake(double magnitude, String location) {
this.magnitude = magnitude;
this.location = location;
}
// getters
}
我尝试过建议here 进行自定义反序列化。它给了我错误
预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT
建议我尝试解析 JsonObject 而不是 JsonArray。这是我使用的反序列化器。
public class EarthquakeDeserializer implements JsonDeserializer<ArrayList<Earthquake>> {
@Override
public ArrayList<Earthquake> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// get list of "features"
JsonElement features = json.getAsJsonObject().get("features");
JsonArray earthquakeElements = new JsonArray();
for (JsonElement feature : features.getAsJsonArray()){
JsonElement properties = feature.getAsJsonObject().get("properties");
earthquakeElements.add(properties);
}
Type listType = new TypeToken<ArrayList<Earthquake>>(){}.getType();
return new Gson().fromJson(earthquakeElements, listType);
}
}
关于这里发生了什么的任何想法?
【问题讨论】:
-
您可以通过 Gson 库轻松反序列化这些东西。你能用吗?
-
@JayDangar 我只是遵循改造方式。对Gson还不是很熟悉。主要是我只是想通过反序列化来避免创建太多的类。
标签: java android json api retrofit