Use class name as root key for JSON Jackson serialization

前端 未结 11 2771
长情又很酷
长情又很酷 2020-11-27 18:05

Suppose I have a pojo:

import org.codehaus.jackson.map.*;

public class MyPojo {
    int id;
    public int getId()
    { return this.id; }

    public void          


        
11条回答
  •  情深已故
    2020-11-27 18:19

    I would be interested in hearing the OP's solution for this. I'm having similar issues where my RESTful web service is serializing objects as either XML or JSON for clients. The Javascript clients need to know the wrapping type so that can parse it. Coupling the type to a URI pattern is not an option.

    Thanks.

    Edit: I noticed that Spring MappingJacksonJsonMarshaller adds the wrapping class when marshalling, so I stepped through the code in debug and noticed that Spring passes in a HashMap with a single key-value pair such that the key is the wrapping name and the value is the object. So, I extended JacksonJaxbJsonProvider, override the writeTo() method and added the following:

    HashMap map = new HashMap();
    map.put(value.getClass().getSimpleName(), value);
    super.writeTo(map, type, genericType, annotations, mediaType, httpHeaders,entityStream);
    

    It's a bit of a hack, but it works nicely.

提交回复
热议问题