Home > Software engineering >  Spring & Jackson - JSON list to custom XML
Spring & Jackson - JSON list to custom XML

Time:10-09

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 :

<root>
    <name>Edward</name>
    <streetName1>value1</streetName1>
    <city1>value2</city1>
    <streetName2>value3</streetName2>
    <city2>value4</city2>
</root>

I tried doing this:

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

But what I got was :

<root>
    <name>Edward</name>
    <address>
        <streetName>value1</streetName>
        <city>value2</city>
    </address>
    <address>
        <streetName>value3</streetName>
        <city>value4</city>
    </address>
</root>

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

CodePudding user response:

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> {

    @Override
    public void serialize(Person t, JsonGenerator jg, SerializerProvider sp) throws IOException {
        String streetName = "streetName";
        String city = "city";
        int nStreet = 1;
        int nCity = 1;
        jg.writeStartObject();
        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());

        }
        jg.writeEndObject();
    }

}

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

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