Google的JSON类库 Gson开发者指南(显示null值的json对象创建)

本文展示了如何使用Gson库配置输出null值,并解释了在JSON序列化时使用null值的影响。通过实例演示了如何创建配置了输出null值的Gson实例,并提供了输出null值的具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://hi.baidu.com/lucifinil/item/ac6834db3cab1d3de3108fa2

Null Object SupportThe default behaviour that is implemented in Gson is that null object fields are ignored.  This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java.

Here's how you would configure a Gson instance to output null:  (显式的显示null值,需要创建一下的对象)
Gson gson = new GsonBuilder().serializeNulls().create();

NOTE: when serializing nulls with Gson, it will add a JsonNull element to the JsonElement structure.  Therefore, this object can be used in custom serialization/deserialization.

Here's an example:

public class Foo {
  private final String s;
  private final int i;

  public Foo() {
    this(null, 5);
  }

  public Foo(String s, int i) {
    this.s = s;
    this.i = i;
  }
}

Gson gson = new GsonBuilder().serializeNulls().create();
Foo foo = new Foo();
String json = gson.toJson(foo);
System.out.println(json);

json = gson.toJson(null);
System.out.println(json);

======== OUTPUT ========
{"s":null,"i":5}
null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值