Spring & Jackson – JSON list to custom XML


I have the following input in JSON format (the address list can be longer) :

    "name": "Edward",
    "address": [
            "streetName": "value1",
            "city": "value2"
            "streetName": "value3",
            "city": "value4"

I need to convert it to XML like this :


I tried doing this:

@JacksonXmlElementWrapper(useWrapping = false)
private List<Address> address = new ArrayList<>();

But what I got was :


Please assist me in getting to the desired format ! Any help would be much appreciated ! Thanks!


It is possible to solve your issue with a custom serializer, so if you have a Person class like below :

@JacksonXmlRootElement(localName = "root")
@JsonSerialize(using = PersonSerializer.class)
public class Person {

    private String name;

    private List<Address> address = new ArrayList<>();


You can build a custom PersonSerializer serializer class extending the JsonSerializer class like below :

public class PersonSerializer extends JsonSerializer<Person> {

    public void serialize(Person t, JsonGenerator jg, SerializerProvider sp) throws IOException {
        String streetName = "streetName";
        String city = "city";
        int nStreet = 1;
        int nCity = 1;
        jg.writeStringField("name", t.getName());
        for (Address address : t.getAddress()) {

            jg.writeStringField(streetName + String.valueOf(nStreet++), address.getStreetName());
            jg.writeStringField(city + String.valueOf(nCity++), address.getCity());



Then you can serialize your Person object like below obtaining the xml result you expect :

XmlMapper xmlMapper = new XmlMapper();
//you already have your person object to serialize
String result = xmlMapper.writeValueAsString(person);

Answered By – dariosicily

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published