【发布时间】:2016-04-21 21:32:36
【问题描述】:
我有一些奇怪的 JSON,例如:
[
{
"type":"0",
"value":"my string"
},
{
"type":"1",
"value":42
},
{
"type":"2",
"value": {
}
}
]
基于某个字段,数组中的对象是某种类型。 使用 Gson,我的想法是拥有一个 TypeAdapterFactory,它将这些特定类型的委托适配器发送到 TypeAdapter,但我很想了解一种阅读“类型”字段以了解要创建哪种类型的好方法。 在 TypeAdapter 中,
Object read(JsonReader in) throws IOException {
String type = in.nextString();
switch (type) {
// delegate to creating certain types.
}
}
假设“类型”字段首先出现在我的 JSON 中。有没有一种体面的方法可以消除这种假设?
【问题讨论】: