亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 pojo 序列化為嵌套的 JSON 字典

將 pojo 序列化為嵌套的 JSON 字典

慕娘9325324 2023-04-13 14:26:14
鑒于簡單POJO:public class SimplePojo {    private String key ;    private String value ;    private int thing1 ;    private boolean thing2;    public String getKey() {           return key;    }    ...}我沒有問題序列化成這樣的東西(使用Jackson): {    "key": "theKey",    "value": "theValue",    "thing1": 123,    "thing2": true  }但真正讓我高興的是,如果我可以這樣序列化該對象: {    "theKey" {           "value": "theValue",            "thing1": 123,            "thing2": true     }  }我在想我需要一個自定義序列化器,但我面臨的挑戰是插入一個新字典,例如:@Overridepublic void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider provider) throws IOException {    gen.writeStartObject();    gen.writeNumberField(value.getKey(), << Here be a new object with the remaining three properties >> );}有什么建議么?
查看完整描述

2 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

您不需要自定義序列化程序。您可以利用@JsonAnyGetter注釋生成包含所需輸出屬性的地圖。

下面的代碼采用上面的示例 pojo 并生成所需的 json 表示。

首先,您已使用 注釋所有 getter 方法,@JsonIgnore以便 jackson 在序列化期間忽略它們。將被調用的唯一方法是帶@JsonAnyGetter注釋的方法。


public class SimplePojo {

    private String key ;

    private String value ;

    private int thing1 ;

    private boolean thing2;


    // tell jackson to ignore all getter methods (and public attributes as well)

    @JsonIgnore

    public String getKey() {

        return key;

    }


    // produce a map that contains the desired properties in desired hierarchy 

    @JsonAnyGetter

    public Map<String, ?> getForJson() {

        Map<String, Object> map = new HashMap<>();

        Map<String, Object> attrMap = new HashMap<>();

        attrMap.put("value", value);

        attrMap.put("thing1", thing1);  // will autobox into Integer

        attrMap.put("thing2", thing2);  // will autobox into Boolean

        map.put(key, attrMap);

        return map;

    }

}


查看完整回答
反對 回復 2023-04-13
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

您需要使用writeObjectFieldStart方法來寫入字段并JSON Object以相同的類型打開新的:


class SimplePojoJsonSerializer extends JsonSerializer<SimplePojo> {


    @Override

    public void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        gen.writeStartObject();


        gen.writeObjectFieldStart(value.getKey());

        gen.writeStringField("value", value.getValue());

        gen.writeNumberField("thing1", value.getThing1());

        gen.writeBooleanField("thing2", value.isThing2());

        gen.writeEndObject();


        gen.writeEndObject();

    }

}


查看完整回答
反對 回復 2023-04-13
  • 2 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號