我有以下類別的屬性:傑克遜JSON不裹嵌套對象
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.");
}
}
我也嘗試添加上述Data
類@JsonSerialize
批註,則在Container
類以上吸氣。正如我前面提到的,沒有任何成功。使用我的序列化程序,記錄器記錄消息。
更新2
當我刪除和writeEndObject()
則沒有JSON是returnesd,只有HTTP Status 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; 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 [[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
如果跳過writeStartObject()和writeEndObject()行會發生什麼? –
你應該寫下這個值:writeNumber(id) –
是的,使用'writeNumber(id)'寫作至少在某些情況下工作。輸出是「數據」:1'。但是如果我想在'Data'類中序列化多於一個屬性呢?我試圖在沒有寫入{寫入{開始,結束}對象'的情況下添加'write * Field'方法 – kurochenko