使用Jackson使用没有注释的属性来序列化xml [英] Using Jackson to serialize xml using attributes without annotations
问题描述
我目前正在使用Jackson编写一些代码将旧版POJO序列化为XML,但我需要使用属性而不是子元素来序列化它们。有没有办法使用Jackson而不在遗留类中添加注释?
I am currently writing some code using Jackson to serialize legacy POJOs into XML, but I need them to be serialized using attributes not child elements. Is there a way to do this using Jackson without adding annotations to the legacy classes?
推荐答案
是有没有办法使用Jackson而不在遗留类中添加注释?
Is there a way to do this using Jackson without adding annotations to the legacy classes?
你可以尝试使用混合注释杰克逊。通过这种方式,您可以保留旧版课程,同时享受注释功能。这是如何做。
You can try to use Mix-in annotations in jackson. In this way you can preserve your legacy classes and the same time you will enjoy the annotations feature. Here's how.
Person.class
class Person {
private String username;
private String lastName;
private String address;
private Integer age;
//getters and setters
}
Mixin.class
abstract class Mixin{
@JacksonXmlProperty(isAttribute = true)
abstract String getUsername();
@JacksonXmlProperty(isAttribute = true)
abstract String getLastName();
@JacksonXmlProperty(isAttribute = true)
abstract String getAddress();
@JacksonXmlProperty(isAttribute = true)
abstract String getAge();
}
主要方法
public static void main(String[] args) throws JsonProcessingException {
Person p = new Person("Foo","Bar");
p.setAddress("This address is too long");
p.setAge(20);
ObjectMapper xmlMapper = new XmlMapper();
xmlMapper.addMixInAnnotations(Person.class, MixIn.class);
String xml = xmlMapper.writeValueAsString(p);
System.out.println(xml);
}
输出
<Person xmlns="" username="Foo" lastName="Bar" address="This address is too long" age="20"></Person>
这篇关于使用Jackson使用没有注释的属性来序列化xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!