我目前正在使用 Jackson 编写一些代码以将遗留 POJO 序列化为 XML,但我需要使用属性而不是子元素对它们进行序列化。有没有办法在不向遗留类添加注释的情况下使用 Jackson 来做到这一点?
最佳答案
Is there a way to do this using Jackson without adding annotations to the legacy classes?
你可以尝试使用Mix-in jackson 的注释。通过这种方式,您可以保留您的遗留类,同时您将享受注释功能。就是这样。
Person.class
class Person {
private String username;
private String lastName;
private String address;
private Integer age;
//getters and setters
}
混合类
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>
关于java - 使用 Jackson 序列化 xml 使用不带注释的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26837401/