gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:01:14 29 4
gpt4 key购买 nike

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com