如果所有字段都为空,如何设置对象为空?

时间:2018-12-27 14:08:26

标签: json gson deserialization json-deserialization

如果对象的所有字段都为空,如何将其设置为空?

反序列化

Gson gson = new Gson();
DetailUser detailUser = gson.fromJson(json, DetailUser.class);

DetailUser ,如果断开连接的所有字段均为空,则该连接应为空

public class DetailUser {
    String email;
    Integer age;
    Disconnect disconnect;
}

断开连接

public class Disconnect {
    String text;
    String beginning;
    String end;
}

JSON disconnect应该为空

{
    "email":"test@test.test",
    "age":33,
    "disconnect":{}
}

JSON disconnect应当为空

{
    "email":"test@test.test",
    "age":33,
    "disconnect":{
                  "text":"test",
                  "beginning":"test",
                  "end":"test"
                 }
}

我希望detailUser.getDisconnect()==nulltrue,但是当false字段(文本,开头,结尾)均为Disconnect时得到null

1 个答案:

答案 0 :(得分:1)

您的问题是您的json中有一个Disconnect对象,该对象的所有字段均为null。 Gson可以按照自己的方式工作,但是如果您希望在所有字段为Disconnect时都将null设置为null,则可以选择一些方法。

一种选择是创建自定义JsonDeserializer,例如:

public class NullAdapter implements JsonDeserializer<Disconnect> {
    @Override
    public Disconnect deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context)
            throws JsonParseException {
        Disconnect dc = new Gson().fromJson(json, typeOfT);
        // Here you decide the criteria in which case to return the Disconnect or null
        // I decided that if any of its fields is not null it is neither null
        if (dc.beginning != null || dc.text != null || dc.end != null) {
            return dc;
        }
        return null;
    }
}

通过向GsonBuilder()注册进行测试:

@Test
public void test() {
    DetailUser du = new GsonBuilder()
            .registerTypeAdapter(Disconnect.class, new NullAdapter())
            .create()
            .fromJson(**YOUR_NULL_JSON**, DetailUser.class);
    assertNull(du.disconnect);
}