如果我有一个简单的对象,如下所示:
String name;
String email;
int age;
boolean isDeveloper;
然后假设接收到的JSON对象具有值:
{"name":null,"email":null,"age":26,"isDeveloper":true}
使用GSON作为默认值反序列化此JSON时,我有:
{"age":26,"isDeveloper":true}
但是电子邮件字段丢失会在以后导致我的应用程序失败,所以我想添加
email = null;
序列化回JSON,并且只有此字段值为null。也不要忽略任何非null字段。
其他空值不应添加到结果JSON中。
我尝试使用默认的GSON构建器进行反序列化,然后使用允许空值的GSON进行序列化:
Gson gson = new GsonBuilder().serializeNulls().create();
问题是:这将查找对象类中的所有null / empty值并将其全部设置
{"name":null,"email":null,"age":26,"isDeveloper":true}
如何设置电子邮件属性为null,然后序列化回仅包含此字段为JSON的JSON,而不忽略任何其他非null值?
我正在使用gson v2.2.4
这是示例代码:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class App
{
private class UserSimple {
public String name;
public String email;
public int age;
public boolean isDeveloper;
UserSimple(String name, String email, int age, boolean isDeveloper) {
this.name = name;
this.email = email;
this.age = age;
this.isDeveloper = isDeveloper;
}
}
public static void main( String[] args )
{
String userJson = "{'age':26,'email':'abc@dfg.gh','isDeveloper':true,'name':null}";
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();
Gson gsonBuilder = new GsonBuilder().serializeNulls().create();
UserSimple deserializedObj = gson.fromJson(userJson, UserSimple.class);
System.out.println("\n"+gson.toJson(deserializedObj));
deserializedObj.email = null;
String serializedObj = gsonBuilder.toJson(deserializedObj, UserSimple.class);
System.out.println("\n"+serializedObj);
}
}
答案 0 :(得分:4)
您可以创建自己的自定义适配器来解决当前的问题:
class MyCustomTypeAdapter extends TypeAdapter<UserSimple> {
@Override
public void write(JsonWriter writer, UserSimple userSimple) throws IOException {
writer.beginObject();
if(userSimple.getName() != null){
writer.name("name");
writer.value(userSimple.getName());
}
// you want to include email even if it's null
writer.name("email");
writer.value(userSimple.getEmail());
if(userSimple.getAge() != null){
writer.name("age");
writer.value(userSimple.getAge());
}
if(userSimple.getDeveloper() != null){
writer.name("isDeveloper");
writer.value(userSimple.getDeveloper());
}
writer.endObject();
}
public UserSimple read(JsonReader reader) throws IOException {
// you could create your own
return null;
}
}
输入:
String userJson = "{'age':null,'email':null,'isDeveloper':true,'name':'somename'}";
输出:
serializedObj :{"name":"somename","email":null,"isDeveloper":true}
输入:
String userJson = "{'age':20,'email':null,'isDeveloper':true,'name':'somename'}";
输出:
serializedObj :{"name":"somename","email":null,"age":20,"isDeveloper":true}
看看https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html
答案 1 :(得分:1)
您是否考虑过使用杰克逊?我认为它比Gson更强大,更快捷。但这只是我的意见,我并不是要冒犯任何人。我还遇到过杰克逊可以做gson无法做的事情。
以下是为您完成工作的代码:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class Main {
static class Person {
@JsonInclude(JsonInclude.Include.ALWAYS)
private String name;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String email;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer age;
public Person(String name, String email, Integer age) {
this.name = name;
this.email = email;
this.age = age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public Integer getAge() {
return age;
}
}
public static void main(String[] args) throws Exception {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); // pretty printing only enabled for demonstration purposes
String test = ow.writeValueAsString(new Person(null, null, 2));
System.out.println(test);
}
}
输出为:
{
"name" : null,
"age" : 2
}
name
也被输出,因为其包含策略为JsonInclude.Include.ALWAYS
。
在Maven中,依赖项包括:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
还有一个答案:Gson serialize null for specific class or field,但看起来还不是很好。