【发布时间】:2021-02-08 16:59:06
【问题描述】:
我正在尝试将 json 字符串中的坐标解析到程序中的 Location 类中。我已经将json文件读入字符串变量coords。问题是字符串包含多个坐标,但我只需要 importantPlace lat 和 lng 而没有其他坐标或信息,但我不知道如何只使用 json 字符串的这些部分来制作新的Location 对象。
Location 类:
public class Location {
public double lat;
public double lng;
public Location(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
}
这是coords 包含的内容:
{
"country": "US",
"square": {
"northeast": {
"lng": 5.18232,
"lat": 42.91431
}
"southwest": {
"lng": 5.18240,
"lat": 42.91422
},
},
"importantPlace": "Building",
"coordinates": {
"lng": 5.18234,
"lat": 42.91427
},
"words": "trades.rare.cable",
"map": "https://w3w.co/trades.rare.cable"
}
我知道要解析我可以使用的所有内容:
public Location parseCoords(String coords) {
Location pos = new Gson().fromJson(coords, Location.class);
return pos;
但这行不通,因为 json 字符串有多个 Location 类没有的坐标和参数。
有没有办法只使用importantPlace lat 和lng 坐标来创建一个新的Location 对象?
【问题讨论】:
-
您需要将payload反序列化为
com.google.gson.JsonObject,找到必填字段并将其转换为类:JsonObject root = gson.fromJson(jsoPayload, JsonObject.class);Location coordinates = gson.fromJson(root.get("coordinates"), Location.class);