Java – JSON does not contain properties of nested objects
I have the following courses:
public class Container { private String name; private Data data; } public class Data { private Long id; }
When I use Jackson to serialize container classes, I get
{"name":"Some name","data":{"id":1}}
But what I need is:
{"name":"Some name","id":1}
Can I (without adding the container. Getdataid () method)? If so, what should I do?
to update
I tried to create a custom jsonserializer < data > but the result was the same as before
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."); } }
I also tried to add the @ jsonserialize annotation on the data class, and then add getters in the container class As mentioned earlier, there was no success My serializer is used to log messages
Update 2
When I delete writestartobject() and writeendobject(), then no JSON is returnsd, only HTTP status 500 error and no exception is thrown, except that I found it in the debugging output
DEBUG: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: 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 [com.example.DataController@16be8a0]: 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 [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name,expecting a value
Solution
Jackson 1.9 has introduced the JSON unwrapped annotation, which is what you're looking for