我从网络API收到一个像这样的JSON:
{
...
"foobar":
{
"type": "...",
"keyTypeA": "value"
}
}
foobar
具有不同的对象类型,具体取决于其type
字段。
因此,foobar
可以是:
{
"type": "typeA",
"keyA1": "...",
"keyA2": "...",
...
}
或
{
"type": "typeB",
"keyB1": "...",
"keyB2": "...",
...
}
等
如何将这些JSON模型解析为我在此定义的POJO类:
public class FoobarTypeBase {
@SerializedName("type")
public String type;
}
public class FoobarTypeA extends FoobarTypeBase {
@SerializedName("keyA1")
public SomeObject keyA1;
@SerializedName("keyA2")
public SomeObject keyA2;
}
public class FoobarTypeB extends FoobarTypeBase {
@SerializedName("keyB1")
public SomeObject keyB1;
@SerializedName("keyB2")
public SomeObject keyB2;
}
我想我必须处理TypeAdapterFactory
和TypeAdapter
,但我不知道如何有效地做到这一点。
答案 0 :(得分:1)
我通常使用Retrofit + Gson的组合,并且这样做:
RuntimeTypeAdapterFactory<FoobarTypeBase> itemFactory = RuntimeTypeAdapterFactory
.of(FoobarTypeBase.class, "type") // The field that defines the type
.registerSubtype(FoobarTypeA.class, "foobar")
.registerSubtype(FoobarTypeB.class) // if the flag equals the class name, you can skip the second parameter.
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(itemFactory)
.create();
然后我像这样初始化Retrofit:
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(BASE_URL);
builder.addConverterFactory(GsonConverterFactory.create(gson));
Retrofit retrofit = builder.build();