天天看點

jackson json 嵌套對象,Jackson JSON不會包裝嵌套對象的屬性

jackson json 嵌套對象,Jackson JSON不會包裝嵌套對象的屬性

I've got following classes:

public class Container {

private String name;

private Data data;

}

public class Data {

private Long id;

}

When I serialize Container class using Jackson I get

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

But I need the result to be:

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

Is it possible (without adding Container.getDataId() method)? If so, how to do it?

update

I've tried to create custom JsonSerializer but the result was same as before

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

}

}

I've also tried to add @JsonSerialize annotation above Data class, then above getter in Container class. As I mentioned before without any success. My serializer is used, logger logs message.

update 2

When I remove writeStartObject() and writeEndObject() then no JSON is returnesd, only HTTP Status 500 error and no exception is thrown except of what I found in debug output.

DEBUG: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.example.Dat[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

解決方案

Jackson 1.9 has introduced JsonUnwrapped annotation which does what you are looking for.