如果对象的所有字段都为空,如何将其设置为空?
反序列化
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()==null
为true
,但是当false
字段(文本,开头,结尾)均为Disconnect
时得到null
。
答案 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);
}