:私はジャクソンを使用してContainer
クラスをシリアル化するときジャクソン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<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は、唯一HTTP Status 500
エラーreturnesdされず、例外は私がデバッグ出力に見つけたものを除いてスローされません。
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)'を使った書き込みは少なくともいくつかの場合に働きました。出力は '' data ':1'でした。しかし、もし私が 'Data'クラスで属性を2つ以上直列化したいのであれば?私は 'Write {Start、End} Object'の有無にかかわらず' write * Field'メソッドを追加しようとしました – kurochenko