第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

GSON 輸出空數(shù)組值

GSON 輸出空數(shù)組值

繁星淼淼 2023-09-06 16:40:52
這是我的 GSON 實(shí)例,因?yàn)槟床坏?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],我也嘗試創(chuàng)建一個(gè)適配器,但沒(méi)有成功:@Overridepublic 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());}為什么輸出包含空值以及如何消除它們?
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

您可以像這樣編寫(xiě)自定義 JSON 序列化器適配器:


public class CustomJsonArraySerializer<T> implements JsonSerializer<T[]> {

    @Override

    public JsonElement serialize(T[] source, Type type, JsonSerializationContext context) {

        JsonArray jsonArray = new JsonArray();

        for(T item : source){

            if(item != null) { // skip null values

                jsonArray.add(context.serialize(item));

            }

        }

        return jsonArray;

    }

}

您可以像這樣注冊(cè)這個(gè)自定義序列化器采用者:


private static final Gson GSON = new GsonBuilder().registerTypeAdapter(Item[].class, new CustomJsonArraySerializer<>()).create();

現(xiàn)在,當(dāng)您序列化它時(shí),Item[]它將忽略這些null值。


測(cè)試:


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}]


查看完整回答
反對(duì) 回復(fù) 2023-09-06
  • 1 回答
  • 0 關(guān)注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)