天天看點

jackson json 嵌套對象_java – 傑克遜JSON不包含嵌套對象的屬性

我有以下課程:

public class Container {

private String name;

private Data data;

}

public class Data {

private Long id;

}

當我使用傑克遜序列化容器類時,我得到

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

但我需要的結果是:

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

是否可以(不添加Container.getDataId()方法)?如果是這樣,怎麼辦?

更新

我試圖建立自定義JsonSerializer< Data>但結果與以前相同

public class JsonDataSerializer extends JsonSerializer {

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.");

}

}

我還試圖在Data類之上添加@JsonSerialize注釋,然後在Container類中添加getter.如前所述,沒有任何成功.我的串行器被使用,記錄器日志消息.

更新2

當我删除writeStartObject()和writeEndObject(),然後沒有JSON是returnesd,隻有HTTP狀态500錯誤,沒有異常抛出,除了我在調試輸出中找到.

DEBUG: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [[email protected]]: 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 [[email protected]]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name,expecting a value

DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [[email protected]]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name,expecting a value