marciel.deg
marciel.deg

Reputation: 512

Jackson XML - change tag according to the property type

How can I change a root tag from a property according to the class type of a property?

Consider this code:

public class Animal {
  private String name;
}

public class Dog extends Animal {
}

public class Cat extends Animal {
}

public class Person {
  private String name;
  private Animal pet;
}

Person p1 = new Person("P1");
p1.setPet(new Dog("Pluto"));
System.out.println(new XMlMapper().writeValueAsString(p1));

Person p2 = new Person("P2");
p2.setPet(new Cat("Tom"));
System.out.println(new XMlMapper().writeValueAsString(p2));

I want this output:

<person>
  <name>P1</name>
  <dog>
    <name>Pluto</name>
  </dog>
</person>

<person>
  <name>P2</name>
  <cat>
    <name>Tom</name>
  </cat>
</person>

How can I do it using Jackson?

Upvotes: 0

Views: 87

Answers (0)

Related Questions