我从网络 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
但我不知道如何有效地完成它。
最佳答案
我通常使用 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();
关于java - 根据字段动态创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930797/