我有一些 XML,我想使用 Jackson FasterXML 将其转换为对象。 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 类中的地址列表,而无需使用 AddressWrapper 类来表示 <addresses>
节点?同样,获取整个 xml 并直接填充 Service 类,而不需要 ServiceWrapper 类?
最佳答案
避免编写/维护此类代码的正常方法是使用 JAXB 生成 Java 代码(带有适当的注释)。此过程使用 XML 架构 (.xsd) 作为输入,并使用可选的绑定(bind)文件 (.xjb) 来自定义生成的代码。
它看起来像许多 JAXB 注释 are supported by Jackson .
我还要指出,JAXB 代码生成器 (xjc) 支持插件,这些插件允许您执行几乎任何您想要增强生成的代码的操作(例如,使用其他方法或注释)。
关于java - 如何在没有多个包装类的情况下反序列化 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39983229/