Jackson JSON不会包装嵌套对象的属性

kur*_*nko 10 java serialization spring json jackson

我有以下课程:

public class Container {
    private String name;
    private Data data;
}

public class Data {
    private Long id;
}
Run Code Online (Sandbox Code Playgroud)

当我Container使用Jackson 序列化课程时,我得到了

{"name":"Some name","data":{"id":1}}
Run Code Online (Sandbox Code Playgroud)

但我需要的结果是:

{"name":"Some name","id":1}
Run Code Online (Sandbox Code Playgroud)

是否有可能(没有添加Container.getDataId()方法)?如果是这样,怎么办?


更新

我试图创建自定义,JsonSerializer<Data>但结果与以前一样

public class JsonDataSerializer extends JsonSerializer<Data> {

    private static Logger logger = Logger.getLogger(JsonDataSerializer.class);

    @Override
    public void serialize(Data value, JsonGenerator jgen, 
            SerializerProvider provider)
            throws IOException,JsonProcessingException {

        Long id = (value.getId() == null) ? 0l : value.getId();
        jgen.writeStartObject();
        jgen.writeNumberField("id", id);
        jgen.writeEndObject();
        logger.debug("Data id " + id + " serialized to JSON.");       
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试在类上面添加@JsonSerialize注释Data,然后在Container类中添加getter .正如我之前提到的,没有任何成功.使用我的序列化程序,记录器记录消息.


更新2

当我删除writeStartObject(),并writeEndObject()再没有JSON是returnesd,只有HTTP Status 500错误并不会引发任何异常的,除了我在调试输出中.

DEBUG: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name, expecting a value; nested exception is org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value
DEBUG: org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name, expecting a value; nested exception is org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value
DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name, expecting a value; nested exception is org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value
Run Code Online (Sandbox Code Playgroud)

小智 10

Jackson 1.9引入了JsonUnwrapped注释,可以满足您的需求.