将适配器用于特定属性(Retrofit2)

时间:2019-11-26 20:12:09

标签: android gson realm retrofit2 typeconverter

我有一个使用RealmObjects的android应用程序,我需要使用Retrofit2与服务器通信其中一些模型。 在这些RealmObjects之一中,有一个属性,我想使用特定的GsonAdapter来反序列化此属性。

除该特定属性外,我如何对realmObject使用默认的GsonConverter?

改造生成器:

CardService cardService = new Retrofit.Builder()
            .baseUrl(CardService.ENDPOINT)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(CardService.class);

特定的realmObject:

public class Card extends RealmObject implements Parcelable {
private int id;
private int cardMarketId;
private String number;
private String name;

private CardRarity rarity;
private boolean awakened;
private RealmList<CardColor> colors;
private CardSerie serie;
private CardType type;
private RealmList<Skill> skills;
private Integer power;
private Integer cost;
private RealmList<ColorCost> colorCosts;
private Integer combo;
private Integer comboCost;
private String character;
private String origin;
private String era;

我要使用特定适配器的特定属性“稀有”的适配器:

public class RarityGsonAdapter extends TypeAdapter<CardRarity> {
public CardRarity read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }
    String rarityEnum = reader.nextString();
    return new CardRarity(RarityEnum.valueOf(rarityEnum));
}
public void write(JsonWriter writer, CardRarity value) throws IOException {
    if (value == null) {
        writer.nullValue();
        return;
    }
    writer.value(value.getEnum().name());
}

}

谢谢您的帮助!

0 个答案:

没有答案