@JsonAnyGetter 将 Map 序列化为扁平的属性

@JsonAnyGetter 注解的方法必须是非静态的、无参数的,且返回值必须为 java.util.Map。序列化时,Map 的条目会被扁平化(与对象其他的属性位于同一级别,与 @JsonUnwrapped 的处理方式相同),而不是作为嵌套属性被序列化。

Example

POJO

public class ScreenInfo {
    private String id;
    private String title;
    private int width;
    private int height;
    private Map<String, Object> otherInfo;
	...

    @JsonAnyGetter
    public Map<String, Object> getOtherInfo() {
        return otherInfo;
    }

    public void addOtherInfo(String key, Object value) {
        if (this.otherInfo == null) {
            this.otherInfo = new HashMap<>();
        }
        this.otherInfo.put(key, value);
    }
    ...
}

序列化

public class MainScreenInfoSerialization {
    public static void main(String[] args) throws IOException {
        ScreenInfo si = new ScreenInfo();
        si.setId("TradeDetails");
        si.setTitle("Trade Details");
        si.setWidth(500);
        si.setHeight(300);
        si.addOtherInfo("xLocation", 400);
        si.addOtherInfo("yLocation", 200);

        System.out.println("-- before serialization --");
        System.out.println(si);

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(si);
        System.out.println("-- after serialization --");
        System.out.println(jsonString);
    }
}

xLocation、yLocation 被序列化成了扁平化的属性,而不是嵌套属性

-- before serialization --
ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
-- after serialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200}

不使用 @ JSONAnyGetter

xLocation、yLocation 被序列化成了嵌套属性

-- before serialization --
ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
-- after serialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"otherInfo":{"xLocation":400,"yLocation":200}}

原文链接

Jackson JSON - Using @JsonAnyGetter Annotation to serialize any arbitrary properties

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值