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

时间:2011-08-08 13:47:03

标签: java json spring serialization jackson

我有以下课程:

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

public class Data {
    private Long id;
}

当我使用杰克逊序列化Container课时我得到了

{"name":"Some name","data":{"id":1}}

但我需要结果:

{"name":"Some name","id":1}

是否可以(不添加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.");       
    }
}

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


更新2

当我删除writeStartObject()writeEndObject()时,没有JSON返回,只有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

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:0)

我认为您必须为数据类型创建并注册自定义序列化程序。

您可以在Data类上使用@JsonSerialize注释。

指定序列化程序类:

@JsonSerialize(using = MyDataSerializer.class)
public class Data {
    ...
}

public static class MyDataSerializer extends JsonSerializer<Data> {

    @Override
    public void serialize(Data value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,JsonProcessingException {
        jgen.writeNumberField("id", value.id);
    }