我从API得到响应,因为如果存在数据,那么它就是返回对象,而当数据不存在时,它就是返回空白数组.
我有用于序列化此模型的模型.
这是模特班
@SerializedName("local")
public Local _local = new Local();
public class Local{
@SerializedName("total")
public String _total;
@SerializedName("providers")
public ArrayList<ProvidersDetails> _providers = new ArrayList<>();
public class ProvidersDetails{
@SerializedName("id")
public String _id;
@SerializedName("image")
public String _image;
}
@SerializedName("admin")
public transient Admin admin = new Admin();
public class Admin{
@SerializedName("id")
public String _id;
@SerializedName("first_name")
public String _first_name;
@SerializedName("last_name")
public String _last_name;
}
@SerializedName("orgn")
public Organization _organization = new Organization();
public class Organization{
@SerializedName("name")
public String _ name;
}
}
这是我从api获得的部分响应
"local":{
"providers":[
{
"id":"1180",
"image":"photo.png"
},
{
"id":"1180",
"image":"photo.png"
},
{
"id":"1180",
"image":"photo.png"
}
],
"admin":{
"id":"1180",
"first_name":"nqgnerq",
"last_name":"gnejbeqp",
},
"orgn":{
"name":"organization name"
}
}
这是当数据不存在时我得到的另一种形式
"local":{
"total":0,
"providers":[
],
"admin":[
],
"orgn":{
"name":"organization name"
}
}
我检查了许多变通方法,但都失败了,因为我想在我的pojo课堂中处理它.有任何解决办法,请提出建议.
解决方法:
您可以使用“ JsonDeserializer”进行处理.这里是一个示例.
使类ProvidersDetails实现Serializable
创建一个这样的新类
public class ProvidersDetailsList {
public ArrayList<ProvidersDetails> getDetails() {
return providersDetails;
}
ArrayList<ProvidersDetails> providersDetails= new ArrayList<>();
}
现在编写反序列化器.
public class PhotoAlbumDeserializer implements JsonDeserializer {
@Override
public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
ProvidersDetailsList providersDetailsList= new ProvidersDetailsList ();
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject != null) {
JsonElement usersField = jsonElement.getAsJsonObject().get("providers");
if (usersField == null || usersField.isJsonNull() || usersField.isJsonPrimitive())
; // if is null or is a primitive type will return an empty result
else if (usersField.isJsonObject()) {
providersDetailsList.getDetails().add((ProvidersDetails) jsonDeserializationContext.deserialize(usersField, ProvidersDetails.class));
} else if (usersField.isJsonArray()) {
Type listOfUserType = new TypeToken<List<ProvidersDetails>>() {
}.getType();
providersDetailsList.getDetails().addAll((Collection<? extends ProvidersDetails>) jsonDeserializationContext.deserialize(usersField, listOfUserType));
}
}
return providersDetailsList;
}
}
现在这样称呼它
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(ProvidersDetailsList.class, new PhotoAlbumDeserializer());
Gson gson = gsonBuilder.create();
ArrayList<ProvidersDetails> providersDetails = gson.fromJson(jsonString, ProvidersDetailsList.class);
这是使用Gson https://*.com/a/16591621/3111083做到的链接