Spring中的非必需JSON属性(杰克逊映射)(Non Required JSON attribute in Spring (Jackson Mapping))

编程入门 行业动态 更新时间:2024-10-25 07:25:38
Spring中的非必需JSON属性(杰克逊映射)(Non Required JSON attribute in Spring (Jackson Mapping))

我在Spring控制器中有这个功能:

@RequestMapping(value = "/*", method = RequestMethod.POST) @ResponseBody @Consumes("application/json") public JSONresponse alta(@RequestBody JSONrequest parametros, HttpServletRequest request) { some code...}

JSON请求是一个像这样的JavaClass:

public class JSONrequest { private String code; private String message; //getters and setter}

我正在使用杰克逊来映射这个,并且正常工作。 但我的问题是:有可能使消息属性不需要吗? 我希望Web服务接受具有这两个属性的JSON或仅接受“code”属性

I have this function in a Spring controller:

@RequestMapping(value = "/*", method = RequestMethod.POST) @ResponseBody @Consumes("application/json") public JSONresponse alta(@RequestBody JSONrequest parametros, HttpServletRequest request) { some code...}

JSON request is a JavaClass like this:

public class JSONrequest { private String code; private String message; //getters and setter}

I'm using Jackson to map this, and works correctly. But my question is: It's possible make message attribute non required? I would like the web service to accept JSON with both attributes or only with the "code" attribute

最满意答案

您可以使用JsonProperty的必需属性。 但此属性可从2.7.x或更高版本获得。

public class JSONrequest { @JsonProperty(value ="CODE",required = true) private String code; @JsonProperty(value ="MESSAGE",required = false) private String message;

上面的代码使属性成为必需的,而message作为反序列化的可选字段。

You can use required property of JsonProperty. But this property is available from 2.7.x or higher versions.

public class JSONrequest { @JsonProperty(value ="CODE",required = true) private String code; @JsonProperty(value ="MESSAGE",required = false) private String message;

Above example makes code attribute as mandatory while message as an optional field for deserialization.

更多推荐

本文发布于:2023-08-03 09:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:杰克逊   属性   JSON   Spring   Mapping

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!