Android GSON反序列化删除空数组 [英] Android GSON deserialize delete empty arrays

查看:409
本文介绍了Android GSON反序列化删除空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GSON和Retrofit。



DTO:

 我想禁用空的数组字段反序列化。公共类实体实现Serializable {

@SerializedName(body)
@Expose
私人BodyObject正文;

我使用 rest API 。如果body字段为空,那么它会发送空的 Array

  { 
body:[]
}

/ strong>

  java.lang.IllegalStateException:预期的BEGIN_OBJECT,但在第1行的BEGIN_ARRAY列443路径$ .body 

如果正文被填充,那么它们会发送正确的Object。

  {
body:{
und:[
{
value:Test ... 。,
summary:,
format:filtered_html,
safe_value:< p>测试....< / p> \\ \\ n,
safe_summary:
}
]
}
}



$ g $ g $ gson gson = new GsonBuilder()
。 setLenient()
.create();

如何删除或禁用这些空阵列反序列化?


<正如Alrama暗示你可以通过创建你自己的 JsonDeserializer 来避免这种情况。



类似于

  public class BodyObjectDeserializer实现了JsonDeserializer< BodyObject> {
@Override
public BodyObject反序列化(JsonElement json,类型typeOfT
,JsonDeserializationContext上下文)
抛出JsonParseException {
try {
return new Gson() .fromJson(json,typeOfT);
} catch(JsonSyntaxException e){
log.warn(Body empty:{},e.getMessage());
}
返回null;


并将其注册到

  Gson gson = new GsonBuilder()
.setLenient()//也许你不需要这个
.registerTypeAdapter(BodyObject.class,new BodyObjectDeserializer())
.create();


I'm using GSON with Retrofit. I want to disable empty array field deserialization.

DTO:

public class Entity implements Serializable {

    @SerializedName("body")
    @Expose
    private BodyObject body;

I work with a rest API. If the body field is empty then it send empty Array:

{
"body": []
}

Exception:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 443 path $.body

If the body is filled, then they send the correct Object.

{
  "body":  {
    "und": [
        {
        "value": "Test ....",
        "summary": "",
        "format": "filtered_html",
        "safe_value": "<p>Test ....</p>\n",
        "safe_summary": ""
        }
    ]
  }
}

-

Gson gson = new GsonBuilder()
                .setLenient()
                .create();

How can I delete, or disable these empty arrays deserializations?

解决方案

As Alrama hinted you could avoid this situation by creating your own JsonDeserializer.

Something like

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;
   }
}

and registering it with your GSON that you use to de-serialize.

Gson gson = new GsonBuilder()
      .setLenient() // maybe you do not need this
      .registerTypeAdapter(BodyObject.class, new BodyObjectDeserializer())
      .create();

这篇关于Android GSON反序列化删除空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆