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.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; 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 [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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值