{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
127.032737,
37.260704
]
}
}
几何中的坐标就是这个。
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[
127.032680,
37.260549
],
[
127.032680,
37.260549
]
]
}
}
当几何中的类型字符串为" LineString"时,几何中的坐标会发生变化。
但是我的几何类是这样的。
public class Geometry {
String type = "";
public List<String> coordinates;
}
所以我想知道如何通过Gson(java class)获取这些动态数据
在我看来,我必须使用反序列化,但我不知道..
答案 0 :(得分:2)
您可以尝试使用JsonDeserializer按照运行时确定的JSON结构对其进行反序列化。
有关详细信息,请查看GSON Deserialiser Example
示例代码:(仅针对Geometry解析逻辑,根据需要进行修改)
class Geometry {
private String type = "";
private List<String> coordinates;
// getter & setter
}
class GeometryDeserializer implements JsonDeserializer<Geometry> {
@Override
public Geometry deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException {
Geometry geometry = new Geometry();
JsonObject jsonObject = json.getAsJsonObject();
JsonElement features = jsonObject.get("features");
String type = "";
List<String> list = new ArrayList<String>();
if (features != null) {
type = features.getAsJsonArray().get(0).getAsJsonObject().get("geometry")
.getAsJsonObject().get("type").getAsString();
} else {
type = jsonObject.get("geometry").getAsJsonObject().get("type").getAsString();
}
if ("LineString".equals(type)) {
JsonArray coordinates = jsonObject.get("geometry").getAsJsonObject()
.get("coordinates").getAsJsonArray();
for (int i = 0; i < coordinates.size(); i++) {
list.add(coordinates.get(i).getAsJsonArray().get(i).getAsString());
}
} else {
JsonArray coordinates = features.getAsJsonArray().get(0).getAsJsonObject()
.get("geometry").getAsJsonObject().get("coordinates").getAsJsonArray();
for (int i = 0; i < coordinates.size(); i++) {
list.add(coordinates.get(i).getAsString());
}
}
geometry.setCoordinates(list);
geometry.setType(type);
return geometry;
}
}
Geometry data = new GsonBuilder()
.registerTypeAdapter(Geometry.class, new GeometryDeserializer()).create()
.fromJson(jsonString, Geometry.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
输出1:
{
"type": "Point",
"coordinates": [
"127.032737",
"37.260704"
]
}
输出2:
{
"type": "LineString",
"coordinates": [
"127.03268",
"37.260549"
]
}
为了更清晰,请查看我的其他帖子: