如何使用列表名称的自定义名称(反)序列化不可变对象?

How to (de)serialize immutable object with custom name for list name?

我正在尝试使用 Jackson 将对象序列化和反序列化为 XML,但是我很难这样做...

我的对象:


    <response id="response-id">
        <messages>
            <message code="a"/>
            <message code="b"/>
        </messages>
    </response>

代码片段:


    public class Playground {
    
        public static void main(String[] args) throws JsonProcessingException {
            Response response = new Response("response-id", List.of(new Message("a"), new Message("b")));
    
            XmlMapper xmlObjectMapper = new XmlMapper(new XmlFactory());
            xmlObjectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            final String value = xmlObjectMapper.writeValueAsString(response);
            System.out.println(value);
            assert ("<response id=\"response-id\"><messages><message code=\"a\"/><message "
                + "code=\"b\"/></messages></response>")
                .equals(value) : "Desired format does not match!";
            final Response deserializedValue = xmlObjectMapper.readValue(value, Response.class);
            //final String deserialized = xmlObjectMapper.writeValueAsString(deserializedValue);
            //assert value.equals(deserialized) : "Does not match";
        }
    }
    
    @JsonInclude(Include.NON_EMPTY)
    @JacksonXmlRootElement(localName = "response")
    @JsonPropertyOrder({"id", "messages"})
    class Response {
    
        private final String id;
        private final List<Message> messages;
    
        @JsonCreator
        public Response(
            @JacksonXmlProperty(localName = "id", isAttribute = true) final String id,
            @JsonProperty("message") final List<Message> messages) {
            this.id = id;
            this.messages = messages;
        }
    
        @JacksonXmlProperty(localName = "id", isAttribute = true)
        public String getId() {
            return id;
        }
    
        @JsonProperty("message")
        @JacksonXmlElementWrapper(localName = "messages")
        public List<Message> getMessages() {
            return messages;
        }
    }
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(Include.NON_EMPTY)
    class Message {
    
        private final String code;
    
        public Message(@JacksonXmlProperty(localName = "code", isAttribute = true) final String code) {
            this.code = code;
        }
    
        @JacksonXmlProperty(localName = "code", isAttribute = true)
        public String getCode() {
            return code;
        }
    }

我做错了什么?我需要使用哪些注释来检索所需的 XML 反序列化输出?

对于未来的 google 员工:

这似乎与 jackson-dataformat-xml 问题有关: https://github.com/FasterXML/jackson-dataformat-xml/issues/187

还发布了解释和解决方法。