鉴于这个班

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>

最佳答案

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

}

10-02 05:22