我有一些奇怪的JSON像:
[
{
"type":"0",
"value":"my string"
},
{
"type":"1",
"value":42
},
{
"type":"2",
"value": {
}
}
]
Run Code Online (Sandbox Code Playgroud)
基于某些字段,数组中的对象是某种类型.使用Gson,我的想法是有一个TypeAdapterFactory将那些特定类型的委托适配器发送到TypeAdapter,但是我想知道读取"type"字段以了解要创建哪种类型的好方法.在TypeAdapter中,
Object read(JsonReader in) throws IOException {
String type = in.nextString();
switch (type) {
// delegate to creating certain types.
}
}
Run Code Online (Sandbox Code Playgroud)
我会假设"类型"字段在我的JSON中排在第一位.有没有一种可行的方法来消除这种假设?