简体   繁体   English

如何在java restful服务中使用json参数

[英]How to consume json parameter in java restful service

How can i consume json parameter in my webservice, I can able to get the parameters using @PathParam but to get the json data as parameter have no clue what to do. 我如何在我的webservice中使用json参数,我可以使用@PathParam获取参数但是获取json数据作为参数不知道该怎么做。

@GET
@Path("/GetHrMsg/json_data")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON)
public String gethrmessage(@PathParam("emp_id") String empid) {

} }

What to use in place of @PathParam and how to parse it later. 用什么代替@PathParam以及以后如何解析它。

I assume that you are talking about consuming a JSON message body sent with the request. 我假设您正在讨论使用随请求发送的JSON消息正文。

If so, please note that while not forbidden outright, there is a general consensus that GET requests should not have request bodies. 如果是的话,请注意,虽然不是完全禁止,有一个GET请求应该要求机构普遍的共识。 See the " HTTP GET with request body " question for explanations why. 有关解释原因,请参阅“ HTTP GET with request body ”问题。

I mention this only because your example shows a GET request. 我之所以提到这一点,只是因为您的示例显示了GET请求。 If you are doing a POST or PUT, keep on reading, but if you are really doing a GET request in your project, I recommend that you instead follow kondu's solution . 如果您正在进行POST或PUT,请继续阅读,但如果您确实在项目中执行GET请求,我建议您改为遵循kondu的解决方案


With that said, to consume a JSON or XML message body, include an (unannotated) method parameter that is itself a JAXB bean representing the message. 话虽如此,要使用JSON或XML消息体,请包含一个(未注释的)方法参数,该参数本身就是表示消息的JAXB bean。

So, if your message body looks like this: 因此,如果您的邮件正文如下所示:

{"hello":"world","foo":"bar","count":123}

Then you will create a corresponding class that looks like this: 然后,您将创建一个如下所示的相应类:

@XmlRootElement
public class RequestBody {
    @XmlElement String hello;
    @XmlElement String foo;
    @XmlElement Integer count;
}

And your service method would look like this: 您的服务方法如下所示:

@POST
@Path("/GetHrMsg/json_data")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void gethrmessage(RequestBody requestBody) {
    System.out.println(requestBody.hello);
    System.out.println(requestBody.foo);
    System.out.println(requestBody.count);
}

Which would output: 哪个会输出:

world
bar
123

For more information about using the different kinds of HTTP data using JAXB, I'd recommend you check out the question " How to access parameters in a RESTful POST method ", which has some fantastic info. 有关使用JAXB使用不同类型的HTTP数据的更多信息,我建议您查看“ 如何访问RESTful POST方法中的参数 ”这一问题,其中包含一些非常棒的信息。

Bertag is right about the comment on the GET. Bertag对GET的评论是正确的。 But if you want to do POST request that consumes json data, then you can refer to the code below: 但是如果你想做消耗json数据的POST请求,那么你可以参考下面的代码:

        @POST
        @Path("/GetHrMsg/json_data")
        @Consumes(MediaType.APPLICATION_JSON)
        public Response gethrmessage(InputStream incomingData) {
            StringBuilder crunchifyBuilder = new StringBuilder();
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
                String line = null;
                while ((line = in.readLine()) != null) {
                    crunchifyBuilder.append(line);
                }
            } catch (Exception e) {
                System.out.println("Error Parsing: - ");
            }
            System.out.println("Data Received: " + crunchifyBuilder.toString());

            // return HTTP response 200 in case of success
            return Response.status(200).entity(crunchifyBuilder.toString()).build();
        }

For referencing please click here 有关参考,请单击此处

@PathParam is used to match a part of the URL as a parameter. @PathParam用于匹配URL的一部分作为参数。 For example in an url of the form http:/example.com/books/{bookid} , you can use @PathParam("bookid") to get the id of a book to a method. 例如,在http:/example.com/books/{bookid}形式的网址中,您可以使用@PathParam("bookid")将图书的ID @PathParam("bookid")给方法。

@QueryParam is used to access key/value pairs in the query string of the URL (the part after the ?). @QueryParam用于访问URL的查询字符串中的键/值对(后面的部分?)。 For example in the url http:/example.com?bookid=1 , you can use @QueryParam("bookid") to get the value of `bookid. 例如,在URL http:/example.com?bookid=1 ,您可以使用@QueryParam("bookid")来获取`bookid的值。

Both these are used when the request url contains some info regarding the parameters and you can use the data directly in your methods. 当请求URL包含有关参数的一些信息时,可以使用这两个参数,您可以直接在方法中使用这些数据。

Please specify the problem in detail if this post doesn't help you. 如果这篇文章对您没有帮助,请详细说明问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM