Tengo siguientes clases:Jackson JSON no envuelva atributos del objeto anidado
public class Container {
private String name;
private Data data;
}
public class Data {
private Long id;
}
Cuando serializar Container
clase utilizando Jackson consigo
{"name":"Some name","data":{"id":1}}
Pero necesito que el resultado sea:
{"name":"Some name","id":1}
¿Es posible (sin agregar el método Container.getDataId()
)? Si es así, ¿cómo hacerlo?
actualización
He tratado de crear la costumbre JsonSerializer<Data>
pero el resultado fue igual que antes
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.");
}
}
También he intentado añadir @JsonSerialize
anotación anterior Data
clase, entonces getter anterior en la clase Container
. Como mencioné antes sin ningún éxito. Mi serializador es usado, el logger registra el mensaje.
actualización 2
Cuando quito writeStartObject()
y writeEndObject()
entonces no JSON es returnesd, solamente HTTP Status 500
error y no es una excepción es lanzada a excepción de lo que encontré en la salida de depuración.
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
¿Qué sucede si omite las líneas writeStartObject() y writeEndObject()? –
probablemente debería simplemente escribir el valor: writeNumber (id) –
Sí, escribir usando simplemente 'writeNumber (id)' funcionó al menos en algunos casos. La salida fue '" datos ": 1'. Pero, ¿y si quiero serializar más de un atributo en la clase 'Data'? Intenté agregar métodos 'write * Field' con y sin' write {Start, End} Object' sin suerte – kurochenko