我有一个返回的API调用:
{
"id": 550,
"favorite": false,
"rated": {
"value": 7.5
},
"watchlist": false
}
或
{
"id": 550,
"favorite": false,
"rated": false,
"watchlist": false
}
所以“rating”字段有时是一个对象或一个布尔值。 我如何用Gson反序列化这样的东西?
我的对象到目前为止看起来像:
public class Status{
@Expose public boolean favorite;
@Expose public Number id;
@Expose public Rated rated;
@Expose public boolean watchlist;
}
public class Rated{
@Expose public Number value;
}
答案 0 :(得分:5)
为了实现这一点,一种方法是实现TypeAdapter<Rated>
- 类似这样的事情:
public class RatedAdapter extends TypeAdapter<Rated> {
public Rated read(JsonReader reader) throws IOException {
reader.beginObject();
reader.nextName();
Rated rated;
try {
rated = new Rated(reader.nextDouble());
} catch (IllegalStateException jse) {
// We have to consume JSON document fully.
reader.nextBoolean();
rated = null;
}
reader.endObject();
return rated;
}
public void write(JsonWriter writer, Rated rated) throws IOException {
if (rated == null) {
writer.value("false");
} else {
writer.value(rated.value);
}
}
}
当您TypeAdapter
到位时,您所要做的就是将其注册到GsonBuilder
并创建新的Gson
,如下所示:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Rated.class, new RatedAdapter());
Gson gson = builder.create();
//Let's try it
Status status = gson.fromJson(json, Status.class);
安装此类型适配器后,Gson将尝试将名为rated
的所有属性转换为适当的Rated
Java对象。