如果默认情况下您不想序列化空值,您可以告诉JsonWriter 仅在您实际读取Address 实例时对其进行序列化。
让我们假设以下类:
class Address {
public String country = "UK";
public String city = "London";
}
现在我们为Address 类创建一个特定的类型适配器。在这里,您明确表示即使 JsonWriter 不应该在响应中写入 null 值,您也允许它仅为 Address 字段这样做(请参阅代码中的 cmets)。
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;
希望对您有所帮助! :-)