我只想为我的 JSON 正文中正在进行 PUT 的一种类型序列化 null。我不想为对象中的任何其他类型序列化空值。我有这样的东西:
public class Patient {
public Address address;
public String first_name;
public String last_name;
}
如果地址为空,我只想序列化地址。例如
Patient patient = new Patient();
patient.address = null;
patient.last_name = "Doe";
看起来像这样:
"address":null,
"last_name":"Doe"
在地址被分配为空的情况下,患者被排除在对象之外,因为默认情况下 Gson 不会序列化我想要的空值,而姓氏保留分配的字符串值。
是否有我可以使用的 Gson 自定义类型适配器?
public class GsonCustomAdapter extends TypeAdapter<Address>
我对这个概念一点都不熟悉,并且已经尝试了一段时间来理解它。非常感谢任何帮助。
最佳答案
如果默认情况下您不想序列化空值,您可以告诉 JsonWriter
只有在您实际读取 Address
实例时才序列化它。
让我们假设以下类:
class Address {
public String country = "UK";
public String city = "London";
}
现在我们为 Address
类创建一个特定类型的适配器。在这里你明确地说,即使 JsonWriter
不应该在响应中写入 null
值,你也允许它这样做只是为了 Address
字段(参见代码中的注释)。
class AddressAdapter extends TypeAdapter<Address> {
@Override
public void write(JsonWriter out, Address address) throws IOException {
if (address == null) {
//if the writer was not allowed to write null values
//do it only for this field
if (!out.getSerializeNulls()) {
out.setSerializeNulls(true);
out.nullValue();
out.setSerializeNulls(false);
} else {
out.nullValue();
}
} else {
out.beginObject();
out.name("country");
out.value(address.country);
out.name("city");
out.value(address.city);
out.endObject();
}
}
@Override
public Address read(JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
in.beginObject();
Address address = new Address();
in.nextName();
address.country = in.nextString();
in.nextName();
address.city = in.nextString();
in.endObject();
return address;
}
}
现在您必须注册此适配器,以便解析器知道在序列化/反序列化 Address
字段时必须使用它。为此,请使用注释 @JsonAdapter
。
class Patient {
@JsonAdapter(AddressAdapter.class)
public Address address;
public String first_name;
public String last_name;
}
完成了!
例如让我们以您的患者为例:
Patient patient = new Patient();
patient.last_name = "Doe";
将解析器设置为序列化空值,您将获得:
{"address":null,"first_name":null,"last_name":"Doe"}
当您不允许时(默认设置):
{"address":null,"last_name":"Doe"}
通过为患者设置地址:
patient.address = new Address();
...
{"address":{"country":"UK","city":"London"},"last_name":"Doe"}
请注意,如果您想在 Java 端坚持命名约定,您可以使用注释 @SerializedName
,例如:
@SerializedName("first_name") public String firstName;
@SerializedName("last_name") public String lastName;
希望对您有所帮助! :-)
关于java - Gson 自定义类型适配器仅在一种对象类型上序列化 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34755811/