如何在没有多个包装类的情况下反序列化XML?

时间:2016-10-11 17:34:16

标签: java xml jackson fasterxml

我想要使用Jackson FasterXML将一些XML变成一个对象。 XML看起来像这样:

<services>
    <service id="1" name="test">
        <addresses>
            <postalAddress id="2" line1="123 Fake Street" city="Springfield" />
        </addresses>
    </service>
</services>

我使用这些类成功地将其反序列化为对象:

JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "services")
public class ServiceWrapper {
    @JacksonXmlProperty(localName = "service")
    private Service service;
    //Getters and setters [...]
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Service {
    @JacksonXmlProperty(isAttribute = true)
    private int id;
    @JacksonXmlProperty(isAttribute = true)
    private String name;
    @JacksonXmlProperty(localName = "addresses")
    private AddressWrapper addresses;
    //Getters and setters [...]
}

public class AddressWrapper {
    @JacksonXmlProperty(localName = "postalAddress")
    private List<Address> addresses;
    //Getters and setters [...]
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    @JacksonXmlProperty(isAttribute = true, localName = "id")
    private int id;
    @JacksonXmlProperty(isAttribute = true, localName = "line1")
    private int address1;
    @JacksonXmlProperty(isAttribute = true, localName = "city")
    private int city;
    //Getters and setters [...]
}

执行映射的代码:

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

ObjectMapper mapper = new XmlMapper(module);
mapper.registerModule(new JSR310Module());
mapper.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, true);

ServiceWrapper serviceWrapper = mapper.readValue(xmlString, ServiceWrapper.class);
return serviceWrapper.getService();

这一切都运行正常,但是使用ServiceWrapper和AddressWrapper类需要很多开销和丑陋的代码;我真正想要的只是<service>节点和<postalAddress>节点中的数据。是否有可能告诉Jackson对象直接填充我的Service类中的Addresses列表而不使用AddressWrapper类来表示<addresses>节点?类似于获取整个xml并直接填充Service类而不需要ServiceWrapper类?

1 个答案:

答案 0 :(得分:0)

避免编写/维护此类代码的常用方法是使用JAXB生成Java代码(带有适当的注释)。此过程使用XML模式(.xsd)作为输入,并使用可选的绑定文件(.xjb)来自定义生成的代码。

它看起来像许多JAXB注释are supported by Jackson

我还要注意,JAXB代码生成器(xjc)支持插件,允许您执行几乎任何想要扩充生成代码的内容(例如,使用其他方法或注释)。

相关问题