如何使用Jackson将其序列化为xml? [英] How to serialize this to xml using Jackson?

查看:232
本文介绍了如何使用Jackson将其序列化为xml?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此类

class Report {
   public String total;
   public Map monthly;

   public Report () {
      total = "10";
      monthly = new HashMap();
      monthly.put("MAR", 5);
      monthly.put("JUN", 5);
   } 
}

我想生成这个XML:

<Report>
    <total>10</total>
    <MAR>5</MAR>
    <JUN>5</JUN>
</Report>

但实际上它产生了这个XML:

But it actually produces this XML:

 <Report>
     <total>10</total>
     <monthly>
         <MAR>5</MAR>
         <JUN>5</JUN>
     </monthly>
</Report>

如果我在<$之前添加 @JsonIgnore c $ c> montly 声明, montly 元素消失了,但总计!?

If I add @JsonIgnore before montly declaration, the montly element goes away, but so does the total!?

<Report>
    <MAR>5</MAR>
    <JUN>5</JUN>
</Report>


推荐答案

为属性添加访问器方法并注释 getMonthly with @ com.fasterxml.jackson.annotation.JsonAnyGetter

Add accessor methods to your attributes and annotate getMonthly with @com.fasterxml.jackson.annotation.JsonAnyGetter.

public class Report {

    private String total;

    private Map monthly;

    public Report () {
        total = "10";
        monthly = new HashMap<>();
        monthly.put("MAR", 5);
        monthly.put("JUN", 5);
    }

    public String getTotal() {
        return total;
    }

    @JsonAnyGetter
    public Map getMonthly() {
        return monthly;
    }

}

这篇关于如何使用Jackson将其序列化为xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆