gson序列化null,Gson序列化特定类或字段的null

I want to serialize nulls for a specific field or class.

In GSON, the option serializeNulls() applies to the whole JSON.

Example:

class MainClass {

public String id;

public String name;

public Test test;

}

class Test {

public String name;

public String value;

}

MainClass mainClass = new MainClass();

mainClass.id = "101"

// mainClass has no name.

Test test = new Test();

test.name = "testName";

test.value = null;

mainClass.test = test;

Creating JSON using GSON:

GsonBuilder builder = new GsonBuilder().serializeNulls();

Gson gson = builder.create();

System.out.println(gson.toJson(mainClass));

Current ouput:

{

"id": "101",

"name": null,

"test": {

"name": "testName",

"value": null

}

}

Desired output:

{

"id": "101",

"test": {

"name": "testName",

"value": null

}

}

How to achieve the desired output?

Preferred solution would have the following properties:

Do NOT serialize nulls by default,

Serialize nulls for fields with a specific annotation.

解决方案

I have interface to check when object should be serialized as null:

public interface JsonNullable {

boolean isJsonNull();

}

And the corresponding TypeAdapter (supports write only)

public class JsonNullableAdapter extends TypeAdapter {

final TypeAdapter elementAdapter = new Gson().getAdapter(JsonElement.class);

final TypeAdapter objectAdapter = new Gson().getAdapter(Object.class);

@Override

public void write(JsonWriter out, JsonNullable value) throws IOException {

if (value == null || value.isJsonNull()) {

//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 {

JsonElement tree = objectAdapter.toJsonTree(value);

elementAdapter.write(out, tree);

}

}

@Override

public JsonNullable read(JsonReader in) throws IOException {

return null;

}

}

Use it as follows:

public class Foo implements JsonNullable {

@Override

public boolean isJsonNull() {

// You decide

}

}

In the class where Foo value should be serialized as null. Note that foo value itself must be not null, otherwise custom adapter annotation will be ignored.

public class Bar {

@JsonAdapter(JsonNullableAdapter.class)

public Foo foo = new Foo();

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值