为简化起见,我将json
字符串的结构如下:
{
"route": {
"bus-1": {
"stations": [
],
"geo": [
]
},
"bus-2": {
"stations": [
],
"geo": [
]
}
},
"routesReverse": {
"bus-1": {
"stations": [
],
"geo": [
]
},
"bus-2": {
"stations": [
],
"geo": [
]
}
}
}
我正在尝试使用
GSON
进行解析:public class MainJson {
@SerializedName("route")
@Expose
public Routes route;
@SerializedName("routesReverse")
@Expose
public Routes routesReverse;
public Routes getRoute() {
return route;
}
public Routes getRoutesReverse() {
return routesReverse;
}
}
我已经创建了所有模型,但是对此模型有一个疑问:
public class Routes {
@SerializedName("bus-1")
@Expose
BusStop busStop1;
@SerializedName("bus-2")
@Expose
BusStop busStop2;
public BusStop getBusStop1() {
return busStop1;
}
public BusStop getBusStop2() {
return busStop2;
}
}
我不喜欢这种为每个总线路线创建带有注释的
BusStop
对象的方法,我想创建诸如List<BusStop>
之类的东西,因为我的json
不仅只有2条路线。如何实现呢?
最佳答案
您可以修改收到的json的结构吗?因为最简单的方法是在“ route” json对象中使用一个名为“ bus”的数组,而不是多个“ bus-i”对象。如果您无法修改json,那么我认为GSON内没有任何方便的解决方案,因为即使您应用了“ alternate”标记,它也可以将对象从1映射到1。签出@SerializedName注释here的文档。