GSON 输出空数组值

这是我的 GSON 实例,因为您看不到 serializeNulls()。


private static final Gson GSON = new GsonBuilder().create();

这就是我生成 json 的方式:


object.add("inventory", GSON.toJsonTree(inventory.getItems()));

物品:


private int id;

private int amount;


public Item(int id, int amount) {

    this.id = id;

    this.amount = amount;

}

输出:


"inventory": [

{

  "id": 13

  "amount": 1,

},

null,

null,

null,

null,

null,

null,

null,

null,

null,

null,

null

],

我也尝试创建一个适配器,但没有成功:


@Override

public JsonElement serialize(Item src, Type typeOfSrc, JsonSerializationContext context) {

    System.out.println(src); // This only prints valid values, no nulls...


    return new Gson().toJsonTree(src, src.getClass());

}

为什么输出包含空值以及如何消除它们?


繁星淼淼
浏览 79回答 1
1回答

蝴蝶不菲

您可以像这样编写自定义 JSON 序列化器适配器:public class CustomJsonArraySerializer<T> implements JsonSerializer<T[]> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public JsonElement serialize(T[] source, Type type, JsonSerializationContext context) {&nbsp; &nbsp; &nbsp; &nbsp; JsonArray jsonArray = new JsonArray();&nbsp; &nbsp; &nbsp; &nbsp; for(T item : source){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(item != null) { // skip null values&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jsonArray.add(context.serialize(item));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return jsonArray;&nbsp; &nbsp; }}您可以像这样注册这个自定义序列化器采用者:private static final Gson GSON = new GsonBuilder().registerTypeAdapter(Item[].class, new CustomJsonArraySerializer<>()).create();现在,当您序列化它时,Item[]它将忽略这些null值。测试:Item[] items = {new Item(10, 20), null, null, null, new Item(50, 60)};JsonElement jsonElement = GSON.toJsonTree(items);System.out.println(jsonElement);输出:[{"id":10,"amount":20},{"id":50,"amount":60}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java