序列化有使用杰克逊酒店指定值的XML元素

问题描述 投票:0回答:1

我试图反序列化/序列化XML内容与下面的元素。

<?xml version="1.0" encoding="utf-8" ?>
<confirmationConditions>
    <condition type="NM-GD" value="something">no modification of guest details</condition>
</confirmationConditions>

我怎样才能正确地创建Java Bean与杰克逊注释正确解析此。我试着JAXB注释和杰克逊失败说,它不能被不必value领域。下面的Java bean我得到了下面的错误。

public class Condition
{
    @JacksonXmlProperty( isAttribute = true, localName = "type" )
    private String type;
    @JacksonXmlProperty( isAttribute = true, localName = "value" )
    private String value;
    private String text;
}

错误

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class Condition), not marked as ignorable (3 known properties: "value", "type", "text"])
 at [Source: (File); line: 3, column: 73] (through reference chain: ConfirmationConditions["condition"]->Condition[""])

基本上我想要的是映射元素含量text场。我无法控制XML因此更改它不会为我工作。

java xml-parsing jackson jaxb jackson2
1个回答
2
投票

你所需要的东西是添加@JacksonXmlText

class Condition {
    @JacksonXmlProperty(isAttribute = true)
    private String type;
    @JacksonXmlProperty(isAttribute = true)
    private String value;
    @JacksonXmlText
    private String text;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

并解析这样说:

    JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(false);
    XmlMapper xmlMapper = new XmlMapper(module);

    xmlMapper.readValue(
            "<condition type=\"NM-GD\" value=\"something\">no modification of guest details</condition>", Condition.class);
© www.soinside.com 2019 - 2024. All rights reserved.