我将 GSON 与 Retrofit 结合使用。我想禁用空数组字段反序列化。
DTO:
public class Entity implements Serializable {
@SerializedName("body")
@Expose
private BodyObject body;
我使用 rest API
。如果 body 字段为空,则它发送空的 Array
:
{
"body": []
}
异常:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 443 path $.body
如果正文已填满,则他们发送正确的对象。
{
"body": {
"und": [
{
"value": "Test ....",
"summary": "",
"format": "filtered_html",
"safe_value": "<p>Test ....</p>\n",
"safe_summary": ""
}
]
}
}
-
Gson gson = new GsonBuilder()
.setLenient()
.create();
如何删除或禁用这些空数组反序列化?
最佳答案
正如 Alrama 所暗示的,您可以通过创建自己的 JsonDeserializer
来避免这种情况。
有点像
public class BodyObjectDeserializer implements JsonDeserializer<BodyObject> {
@Override
public BodyObject deserialize(JsonElement json, Type typeOfT
,JsonDeserializationContext context)
throws JsonParseException {
try {
return new Gson().fromJson(json, typeOfT);
} catch (JsonSyntaxException e) {
log.warn("Body seems empty: {}",e.getMessage());
}
return null;
}
}
并将其注册到您用于反序列化的 GSON
。
Gson gson = new GsonBuilder()
.setLenient() // maybe you do not need this
.registerTypeAdapter(BodyObject.class, new BodyObjectDeserializer())
.create();
关于Android GSON反序列化删除空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830120/