Jackson xml and json root element

后端 未结 1 759
孤街浪徒
孤街浪徒 2021-01-19 22:48

I have a service which returns objects in JSON and XML format.

http://localhost:8091/apiN/xml/2

XML Result



        
1条回答
  •  天涯浪人
    2021-01-19 23:27

    The JSON and XML structures are not equivalent. In XML you want a list of RestObject and in JSON you want a list whose elements wrap instances of RestObject in another object. This isn't something you can get with a simple Jackson annotation, you would need a custom serializer only for JSON serialization. First of all, getting the desired XML format is straightforward:

    class RestObject implements Serializable {
        private LocalDateTime timestamp;
        private String title;
        private String fullText;
        private Long id;
        private Double value;
    }
    
    @JsonRootName("restObjectList")
    class RestObjectList {
        @JacksonXmlProperty(localName = "restObject")
        @JacksonXmlElementWrapper(useWrapping = false)
        private List restObjectList;
    }
    

    If you absolutely want to wrap each element in the array in json you'll need a custom serializer e.g.

    class RestObjectSerializer extends JsonSerializer {
        @Override
        public void serialize(RestObject value, JsonGenerator gen, SerializerProvider serializers) throws
                IOException {
            gen.writeStartObject();
            gen.writeObjectFieldStart("restObject");
            gen.writeObjectField("timeStamp", value.getTimestamp());
            gen.writeStringField("title", value.getTitle());
            // other fields
            gen.writeEndObject();
            gen.writeEndObject();
        }
    }
    

    And register only with the ObjectMapper that serializes JSON so it doesn't interfere with serialization to XML:

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("MyModule");
    module.addSerializer(RestObject.class, new RestObjectSerializer());
    mapper.registerModule(module);
    

    0 讨论(0)
提交回复
热议问题