Spring & Jackson - JSON 自定义列表 XML

Spring & Jackson - JSON list to custom XML

我有以下 JSON 格式的输入(地址列表可以更长):

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

我需要像这样将其转换为 XML :

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

我试过这样做:

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

但我得到的是:

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

请帮助我获得所需的格式!任何帮助将非常感激 !谢谢!

可以使用自定义序列化程序解决您的问题,因此如果您有如下 Person class :

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

    private String name;

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

}

您可以构建自定义 PersonSerializer 序列化程序 class 扩展 JsonSerializer class 如下所示:

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();
    }

}

然后您可以序列化您的 Person 对象,如下所示,以获得您期望的 xml 结果:

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