java – 杰克逊JSON不包含嵌套对象的属性
发布时间:2020-12-14 16:35:46 所属栏目:Java 来源:网络整理
导读:我有以下课程: 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}
我有以下课程:
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类中添加getter.如前所述,没有任何成功.我的串行器被使用,记录器日志消息. 更新2 当我删除writeStartObject()和writeEndObject(),然后没有JSON是returnesd,只有HTTP状态500错误,没有异常抛出,除了我在调试输出中找到. 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 解决方法
杰克逊1.9已经引入了
JsonUnwrapped 注释,它是你正在寻找的.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java – 如何使variatic方法将单个数组作为varargs数组的第
- java – Guava Charmatcher静态初始化慢
- 在Java项目中引用外部模块的最佳实践
- 线程queue、线程进程池,协程
- Java中SpringSecurity密码错误5次锁定用户的实现方法
- kotlin – 可以为Java类添加“static”扩展函数吗?
- 任何Clojure真正闪耀着Java并不是并发/不可变性 – 功能相关
- servlet下载文件实现代码详解(五)
- java – 从mongodb中的嵌套json数组中检索值
- This template did not produce a Java class or an interf