java 从 JAX-RS 中的 JSON 请求获取简单的 JSON 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17970969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:44:34  来源:igfitidea点击:

Get simple JSON Parameter from a JSON request in JAX-RS

javajsonjax-rs

提问by Andrei I

The client/browser makes a JSON request to my rest resource (the content-type of the request is application/jsonand the corresponding REST method is @Consumes("application/json")annotated).

客户端/浏览器向我application/json的 REST资源发出 JSON 请求(请求的内容类型是,并@Consumes("application/json")注释了相应的 REST 方法)。

@Path("/process-something")
@POST
@Produces("application/json")
@Consumes("application/json")
@HandleDefaultExceptions
public AResponse processSomething(List<Long>) {

}

The JSON body consists of some simple types, like List<Long>or String.

JSON 主体由一些简单的类型组成,例如List<Long>or String

Is there a simple possibility to get JSON parameters injected just annotating it somehow, similar to @FormParamin the case of a application/x-www-form-urlencodedrequest? I would like some other easier solutions than decoding the JSON String with Hymanson's ObjectMapperor Jettison's JSONObject.

是否有一种简单的可能性来注入 JSON 参数,只是以某种方式对其进行注释,类似于请求@FormParam的情况application/x-www-form-urlencoded?我想要一些其他更简单的解决方案,而不是使用 HymansonObjectMapper或 Jettison 的JSONObject.

采纳答案by TheArchitect

You may create a Java class that reflects the data model of your JSON object and annotate it with JAXB's @XmlRootElement. You can map the attributes to custom JSON key name with @XmlElement annotations, e.g.:

您可以创建一个反映 JSON 对象数据模型的 Java 类,并使用 JAXB 的 @XmlRootElement 对其进行注释。您可以使用@XmlElement 注释将属性映射到自定义 JSON 键名,例如:

@XmlRootElement
public class MyJSONOject{
    @XmlElement(name="json-key-name")
    public String attribute;
}

Then Jersey can decode the JSON object for you transparently and voila!

然后 Jersey 可以为您透明地解码 JSON 对象,瞧!

@Path("/process-something")
@POST
@Produces("application/json")
@Consumes("application/json")
public AResponse processSomething(MyJSONOject json) {
    log.fine(json.attribute);
}

回答by Andrei I

According to this documentationthere are 6 parameter-based annotations used to extract parameters from a request, and no one seems to be for JSON parameters.

根据这个文档,有 6 个基于参数的注释用于从请求中提取参数,似乎没有一个用于 JSON 参数。