更快xml jackson 使用 Pojo 创建嵌套 xml

fasterxml jackson create nested xml using Pojo

我想创建 xml 如下所示:

<color>black</color>
<size>
<height>1</height>
</size>

我的 Pojo class 是:

public class features {
    private String color;
    @JacksonXmlProperty(localName = "size")
    @JsonProperty("value")
    private Height height;
    //getter, setter, toString

    class Height{
        @JacksonXmlProperty(localName="height")
        public String value;  
        //getter, setter, toString
    }
}

Json 我传递的是: { 颜色:"black", "value":1 }

我得到的输出是:

<color>black</color>
<size>
<height/>
</size>

为什么不将值设置为高度?

你的问题是 Jackson 只能使用静态内部 classes。 More info

像这样的东西应该可以工作

static class Height{
    @JacksonXmlProperty(localName="height")
    public String value;

    public Height() {}

    public Height(String value) {
        this.value = value;
    }

}

其他选项是在功能 class 中使用正确的 setter,例如

@JsonProperty("value")
public void setHeightFromString(String height){
    this.height = new Height();
    this.height.value = height;
}

PS:我假设你的 json 是有效的并且看起来像 { "color":"black", "value":"1" }