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?
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();
}
Main method
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);
}
Output
<Person xmlns="" username="Foo" lastName="Bar" address="This address is too long" age="20"></Person>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With