java - 如何使用 GSON 只返回一个特定的空字段?

标签 java json serialization null gson

如果我有一个简单的对象如下:

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。也不要忽略任何非空字段。

不应将其他空值添加到生成的 JSON 中。

我尝试使用默认的 GSON 构建器进行反序列化,然后使用允许空值的 GSON 进行序列化,如下所示:

Gson gson = new GsonBuilder().serializeNulls().create();

问题是:这将从对象类中查找所有 null/空值并将它们全部设置

{"name":null,"email":null,"age":26,"isDeveloper":true}

如何将电子邮件属性设置为 null,然后序列化回仅包含此字段的 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);


    }
}

最佳答案

您可以创建自己的自定义适配器来解决手头的问题:

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

关于java - 如何使用 GSON 只返回一个特定的空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566126/

相关文章:

java - 如何从 Eclipse Java 动态 Web 项目中的属性文件中读取?

java - 这些 byte[] 在哪里? (在 Java 中使用 JProfiler)

java - Liferay 和 portlet 部署

iphone - PhoneGap.exec() 在 JS 和 Obj-C 之间传递对象

python - 如何在scrapy中使用项目字段对xml进行排序?

java - 使用 jaxb 的 XML 解析器

javascript - 简单请求: Uncaught TypeError: Cannot read property 'length' of undefined

javascript - 解析 JSON 失败,JavaScript 中缺少元素

java - 服务器通过网络使用Java序列化是否存在安全漏洞?

python - 如何从 PNG 图像中获取像素数据以进行 gpg 签名?