簡體   English   中英

Gson通過改變字段類型進行反序列化

[英]Gson deserializing with changing field types

我有一個返回的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對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM