Android 当列表中的单个项的格式不相同时,如何使用Refundation和Gson解析json列表?
我正在使用改造和Gson与服务器通信并解析响应 我正在从服务器接收几何体对象列表。但对象的坐标场可能不同。例如,我正在从服务器接收以下json:Android 当列表中的单个项的格式不相同时,如何使用Refundation和Gson解析json列表?,android,json,parsing,gson,retrofit,Android,Json,Parsing,Gson,Retrofit,我正在使用改造和Gson与服务器通信并解析响应 我正在从服务器接收几何体对象列表。但对象的坐标场可能不同。例如,我正在从服务器接收以下json: { "geometry":{ "type":"Point", "coordinates": [ 76.95210456848145, 43.2790799527603 ] } } 有时此对象以以下格式返回我:
{
"geometry":{
"type":"Point",
"coordinates": [
76.95210456848145,
43.2790799527603
]
}
}
有时此对象以以下格式返回我:
{
"geometry":{
"type":"Polygon",
"coordinates":[
[
[76.9478130340576,43.286265501840916],
[76.9482421875,43.276267985142056],
[76.95098876953125,43.27101863123778]
]
]
}
}
如您所见,在第一个示例中,有时坐标字段只是一个列表。有时,在第二个示例中,此字段是三级深度列表
因此,我无法正确解析列表,因为列表中元素的格式不同
我怎样才能正确地解析它
目前,我正在使用此数据类:
data class Geometry(
@SerializedName("coordinates")
val coordinates: List<List<List<Double>>>,
@SerializedName("type")
val type: String)
如果您知道该文件有两个版本,请为每个文件创建一个内部类。在解析时,确定坐标的类型(如果是第一种类型,则从第一种类型开始),如果是第二种类型,则从第二种类型开始
inner class GeometryV2(
@SerializedName("coordinates")
val coordinates: List<List<List<Double>>>,
@SerializedName("type")
val type: String)
}
inner class GeometryV1(
@SerializedName("coordinates")
val coordinates: List<Double>,
@SerializedName("type")
val type: String)
}