如何使用杰克逊将此序列化为xml?

时间:2018-11-04 00:05:27

标签: java jackson

给这个班

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:

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

如果我在@JsonIgnore声明之前添加montly,则montly元素将消失,但total也会消失!?

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

1 个答案:

答案 0 :(得分:1)

将访问器方法添加到属性中,并用getMonthly注释@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;
    }

}