java – Gson使用不断变化的字段类型进行反序列化

我有一个返回的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;
}
最佳答案
为了使其工作,一种方法是实现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对象.

转载注明原文:java – Gson使用不断变化的字段类型进行反序列化 - 代码日志