JacksonXML注解:带属性的字符串元素

sshcrbum  于 2023-04-30  发布在  其他
关注(0)|答案(3)|浏览(124)

我似乎找不到一种方法来制作Pojo,使用jackson-xml注解生成xml,如下所示:

<Root>
    <Element1 ns="xxx">
        <Element2 ns="yyy">A String</Element2>
    </Element1>
</Root>

我能想到的最接近的是:

根POJO

public class Root {
    @JacksonXmlProperty(localName = "Element1")
    private Element1 element1;

    public String getElement1() {
        return element1;
    }

    public void setElement1(String element1) {
        this.element1 = element1;
    }
}

元素1 POJO

public class Element1 {
    @JacksonXmlProperty(isAttribute = true)
    private String ns = "xxx";
    @JacksonXmlProperty(localName = "Element2")
    private Element2 element2;

    public String getElement2() {
        return element2;
    }

    public void setElement2(String element2) {
        this.element2 = element2;
    }
}

Element2 POJO

public class Element2 {
    @JacksonXmlProperty(isAttribute = true)
    private String ns = "yyy";
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

但这会返回以下内容:

<Root>
    <Element1 ns="xxx">
        <Element2 ns="yyy"><value>A String</value></Element2>
    </Element1>
</Root>

我不想显示“A String”周围的元素标记。

gpfsuwkq

gpfsuwkq1#

您应该为value字段使用JacksonXmlText注解。

public class Element2 
{
    @JacksonXmlProperty(isAttribute = true)
    private String ns = "yyy";
    @JacksonXmlText
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

那么XML看起来就像

<Root>
    <Element1 ns="xxx">
        <Element2 ns="yyy">A String</Element2>
    </Element1>
</Root>
laximzn5

laximzn52#

为了补充flyingAssistant's answer,您不能将@JacksonXmlText添加到构造函数属性。此功能可以添加到构建2中。13基于GitHub存储库中报告的此问题。所以现在你得这么做

data class Element2(@field:JacksonXmlProperty(isAttribute = true) val ns: String = "yyy") {
    @field:JacksonXmlText
    val value: String? = null
}
rqenqsqc

rqenqsqc3#

对于Kotlin,你需要使用@field annotation use-site targets:

data class Element2(
        @field:JacksonXmlProperty(isAttribute = true)
        val ns: String = "yyy",
        @field:JacksonXmlText
        val value: String? = null
)

如果你不喜欢自己定义nsvalue属性的初始值,那么使用Kotlin no-args plugin,它会生成一个默认的构造函数。

相关问题