同一字段具有两种不同的类型,给翻新2的Gson转换器带来麻烦 [英] Same field has two different types gives trouble with Gson converter for Retrofit 2
本文介绍了同一字段具有两种不同的类型,给翻新2的Gson转换器带来麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是json模式:
如您所见,rating既可以是布尔值,也可以是宾语.
As you can see, rated can be both boolean and object.
我正在使用Retrofit 2和Gson转换器.我应该如何为该架构创建模型?
I am using Retrofit 2 and Gson converter. How should I create my model for this schema?
推荐答案
这是我解决此问题的方法:
Here's how I solved this issue:
在模型中创建一个自定义类型的适配器,并手动对其进行解析;
Create a custom type adapter in your model and parse rated manually;
public class AccountState {
//@SerializedName("rated") //NOPE, parse it manually
private Integer mRated; //also don't name it rated
public Integer getRated() {
return mRated;
}
public void setRated(Integer rated) {
this.mRated = rated;
}
public static class AccountStateDeserializer implements JsonDeserializer<AccountState> {
@Override
public AccountState deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
AccountState accountState = new Gson().fromJson(json, AccountState.class);
JsonObject jsonObject = json.getAsJsonObject();
if (jsonObject.has("rated")) {
JsonElement elem = jsonObject.get("rated");
if (elem != null && !elem.isJsonNull()) {
if(elem.isJsonPrimitive()){
accountState.setRated(null);
}else{
accountState.setRated(elem.getAsJsonObject().get("value").getAsInt());
}
}
}
return accountState ;
}
}
}
在这里使用此自定义适配器创建gson:
Here you create your gson with this custom adapter:
final static Gson gson = new GsonBuilder()
.registerTypeAdapter(AccountState.class, new AccountState.AccountStateDeserializer())
.create();
将其添加到这样的改造中:
Add it to retrofit like that:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
TADADADADADADADDAD!
TADADADADADADADDAD!
这篇关于同一字段具有两种不同的类型,给翻新2的Gson转换器带来麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文