如果未使用 Gson (GsonBuilder()) 初始化,如何不写 float

How to not write float if not initialized with Gson (GsonBuilder())

我的 POJO:

public class MyObj{
    String index;
    float spread;
}

我的发电机:

MyObj stub = new MyObj();
stub.setIndex("1234");
// stub.setSpread(0.20f);

我的 toString 方法:

@Override
public String toString() {
    return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter().nullSafe()).create().toJson(this);
}

我的 JSON 结果是:

{
    "index": "1234",
    "spread": 0.0
}

但我想要:

{
    "index": "1234"
}

GSon 默认设置预见到 null 属性 不会出现在结果 JSON 中。如果你想明确地看到这个值,你必须使用 .serializeNulls()。 但是在你的情况下,你有一个 float 值(原始数据类型),即使你没有明确设置它,默认情况下也会初始化为 0 。所以你必须用 Float 值来定义你 class:

public class MyObj{
    String index;
    Float spread;
}

因此 "spread" 字段将不会出现在 Json 序列化中,因为它默认初始化为 null