Java Gson通过更改字段类型进行反序列化
我有一个API调用,它返回:Java Gson通过更改字段类型进行反序列化,java,json,gson,Java,Json,Gson,我有一个API调用,它返回: { "id": 550, "favorite": false, "rated": { "value": 7.5 }, "watchlist": false } 或 所以“额定”字段有时是一个对象或布尔值。 我如何用Gson反序列化类似的东西 到目前为止,我的对象看起来像: public class Status{ @Expose public boolean favorite; @Expose public Number
{
"id": 550,
"favorite": false,
"rated": {
"value": 7.5
},
"watchlist": false
}
或
所以“额定”字段有时是一个对象或布尔值。
我如何用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;
}
为了使其正常工作,一种方法是实现
TypeAdapter
——类似于以下内容:
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);
}
}
}
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对象。在这两种情况下,您希望生成的rated
字段具有什么值?null
或填充对象必须在同一代码中使用不同类型的对象有什么意义?我想你的问题是false的意思是“空”。。。这样的评级甚至应该被取消。
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);