jeudi 13 août 2015

Java XML serialization of lists without wrapping each element in list name and giving each object its root name

Using Jackson XML I have the following code :

public static class Person{}

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@JacksonXmlRootElement(localName = "StudentElement")
public static class Student extends Person{
    private String firstName;
}

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@JacksonXmlRootElement(localName = "TeacherElement")
public static class Teacher extends Person{
    private String firstName;
}


@Getter
@Setter
@AllArgsConstructor
public static class School{
    @JacksonXmlElementWrapper(useWrapping = false)
    Person[] people;
}

public static void main(String[] args) throws Exception {
    XmlMapper xmlMapper = new XmlMapper();

    final School school = new School(new Person[]{
            new Student("John"),
            new Teacher("MR. Jackson")
    });

    String asString = xmlMapper.writeValueAsString(school);

    prettyPrintXml(asString);
}

With output :

<?xml version="1.0" encoding="UTF-8"?><School xmlns="">
  <people>
    <firstName>John</firstName>
  </people>
  <people>
    <firstName>MR. Jackson</firstName>
  </people>
</School>

I am trying to keep name of elements in the array and avoid wrapping each element in people tag. Such as

<?xml version="1.0" encoding="UTF-8"?>
<School xmlns="">
    <people>
        <StudentElement>
            <firstName>John</firstName>
        </StudentElement>
        <TeacherElement>
            <firstName>MR. Jackson</firstName>
        </TeacherElement>
    </people>
</School>

Ideally I would still use Jackson XML but I am not limited to it. Is there a way to get this done without writing a new serializer.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire