JSON Example With RESTEasy + Jackson

In this tutorial we are going to see how you can integrate RESTEasy withJackson to develop JAX-RS RESTful services that produce and consume JSON streams. As you probably know, Jackson is used to marshal a Java Object to JSON, and ummarshal a JSON file (or stream in general) to a Java Object

In this example we are not going to focus on how to create a JAX-RS application from top to bottom. So make sure you read carefully RESTEasy Hello World Example and pay attention to the sections concerning the creation of the project with Eclipse IDE as well as the deployment of the project in Tomcat.

You can create your own project following the instructions on RESTEasy Hello World Example. But you can also download the Eclipse project of this tutorial here : JAXRS-RESTEasy-CustomApplication.zip, and build your new code on top of that.

1. Project structure

For this example, I’ve created a new Project called “RESTEasyJSONExample“. You can see the structure of the NEW project in the image below:

project-structure

At this point you can also take a look at the web.xml file to see how the project is configured:

web.xml:

01 <?xml version="1.0" encoding="UTF-8"?>
05     id="WebApp_ID" version="3.0">
06     <display-name>JAXRS-RESTEasy</display-name>
07  
08     <servlet-mapping>
09         <servlet-name>resteasy-servlet</servlet-name>
10         <url-pattern>/rest/*</url-pattern>
11     </servlet-mapping>
12  
13     <!-- Auto scan REST service -->
14     <context-param>
15         <param-name>resteasy.scan</param-name>
16         <param-value>true</param-value>
17     </context-param>
18  
19     <!-- this should be the same URL pattern as the servlet-mapping property -->
20     <context-param>
21         <param-name>resteasy.servlet.mapping.prefix</param-name>
22         <param-value>/rest</param-value>
23     </context-param>
24  
25     <listener>
26         <listener-class>
27             org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
28             </listener-class>
29     </listener>
30  
31     <servlet>
32         <servlet-name>resteasy-servlet</servlet-name>
33         <servlet-class>
34             org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
35         </servlet-class>
36     </servlet>
37  
38 </web-app>

As you can see our servlet is mapped to /rest/ URI pattern. So the basic structure of the URIs to reach the REST Services used in this example will have the form :

2. Jackson Dependencies

To integrate RESTEasy with Jackson you have to declare the following dependencies in your pom.xml file.

JSON/Jackson Dependencies:

1 <dependency>
2     <groupId>org.jboss.resteasy</groupId>
3     <artifactId>resteasy-jackson-provider</artifactId>
4     <version>3.0.4.Final</version>
5 </dependency>

3. Java class to be represented to JSON

This is the Java class that is going to be represented in JSON format.

Student.java:

01 package com.javacodegeeks.enterprise.rest.resteasy;
02  
03 public class Student {
04  
05     private int id;
06     private String firstName;
07     private String lastName;
08     private int age;
09  
10     // Must have no-argument constructor
11     public Student() {
12  
13     }
14  
15     public Student(String fname, String lname, int age, int id) {
16         this.firstName = fname;
17         this.lastName = lname;
18         this.age = age;
19         this.id = id;
20     }
21  
22     public void setFirstName(String fname) {
23         this.firstName = fname;
24     }
25  
26     public String getFirstName() {
27         return this.firstName;
28     }
29  
30     public void setLastName(String lname) {
31         this.lastName = lname;
32     }
33  
34     public String getLastName() {
35         return this.lastName;
36     }
37  
38     public void setAge(int age) {
39         this.age = age;
40     }
41  
42     public int getAge() {
43         return this.age;
44     }
45  
46     public void setId(int id) {
47         this.id = id;
48     }
49  
50     public int getId() {
51         return this.id;
52     }
53  
54     @Override
55     public String toString() {
56         return new StringBuffer(" First Name : ").append(this.firstName)
57                 .append(" Last Name : ").append(this.lastName)
58                 .append(" Age : ").append(this.age).append(" ID : ")
59                 .append(this.id).toString();
60     }
61  
62 }

4. REST Service to produce JSON output

Let’s see how easy it is with RESTEasy to produce JSON output using a simple Student instance.

RESTEasyJSONServices.java:

01 package com.javacodegeeks.enterprise.rest.resteasy;
02  
03 import javax.ws.rs.Consumes;
04 import javax.ws.rs.GET;
05 import javax.ws.rs.POST;
06 import javax.ws.rs.Path;
07 import javax.ws.rs.PathParam;
08 import javax.ws.rs.Produces;
09 import javax.ws.rs.core.Response;
10  
11 @Path("/jsonServices")
12 public class RESTEasyJSONServices {
13  
14     @GET
15     @Path("/print/{name}")
16     @Produces("application/json")
17     public Student produceJSON( @PathParam("name") String name ) {
18  
19         Student st = new Student(name, "Marco",19,12);
20  
21         return st;
22  
23     }
24  
25 }

After deploying the application, open your browser and go to:

This is the response:

browser

Here is the raw HTTP Response:

HTTP Response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 08 Dec 2013 16:45:50 GMT

{"id":12,"firstName":"James","lastName":"Marco","age":19}

5. REST Service to consume JSON

Here is a REST Service that consumes a simple JSON stream. the JSON object will be parsed and unmarshaled to Studentinstance.

RESTEasyJSONServices.java:

01 package com.javacodegeeks.enterprise.rest.resteasy;
02  
03 import javax.ws.rs.Consumes;
04 import javax.ws.rs.GET;
05 import javax.ws.rs.POST;
06 import javax.ws.rs.Path;
07 import javax.ws.rs.PathParam;
08 import javax.ws.rs.Produces;
09 import javax.ws.rs.core.Response;
10  
11 @Path("/jsonServices")
12 public class RESTEasyJSONServices {
13  
14     @POST
15     @Path("/send")
16     @Consumes("application/json")
17     public Response consumeJSON( Student student ) {
18  
19         String output = student.toString();
20  
21         return Response.status(200).entity(output).build();
22     }
23  
24 }

Now in order to consume that service we have to create a post request and append an XML file to it. For that we are going to use RESTEasy Client API. To use RESTEasy Client API you have to add the following dependency in your pom.xml.

RESTEasy Client API dependency:

1 <dependency>
2     <groupId>org.jboss.resteasy</groupId>
3     <artifactId>resteasy-client</artifactId>
4     <version>3.0.4.Final</version>
5 </dependency>

For this, I’ve created a new class, called RESTEasyClient.java in a new Package calledcom.javacodegeeks.enterprise.rest.resteasy.resteasyclient. So the final Project Structure would be like so:

final-project-structure

Here is the client:

RESTEasyClient.java:

01 package com.javacodegeeks.enterprise.rest.resteasy.resteasyclient;
02  
03 import javax.ws.rs.client.Entity;
04 import javax.ws.rs.core.Response;
05  
06 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
07 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
08 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
09  
10 import com.javacodegeeks.enterprise.rest.resteasy.Student;
11  
12 public class RESTEasyClient {
13  
14     public static void main(String[] args) {
15  
16         Student st = new Student("Catain""Hook"1012);
17  
18         /*
19          *  Alternatively you can use this simple String to send
20          *  instead of using a Student instance
21          
22          *  String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}";
23          */
24  
25         try {
26             ResteasyClient client = new ResteasyClientBuilder().build();
27  
28             ResteasyWebTarget target = client
29                     .target("http://localhost:9090/RESTEasyJSONExample/rest/jsonServices/send");
30  
31             Response response = target.request().post(
32                     Entity.entity(st, "application/json"));
33  
34             if (response.getStatus() != 200) {
35                 throw new RuntimeException("Failed : HTTP error code : "
36                         + response.getStatus());
37             }
38  
39             System.out.println("Server response : \n");
40             System.out.println(response.readEntity(String.class));
41  
42             response.close();
43  
44         catch (Exception e) {
45  
46             e.printStackTrace();
47  
48         }
49  
50     }
51 }

As you can see, we create a simple Student instance and send it to the service via a POST Request. This is the output of the above client:

Outptut:

Server response : 

First Name : Catain Last Name : Hook Age : 10 ID : 12

Here is the raw POST request:

POST Request:

POST /RESTEasyJSONExample/rest/jsonServices/send HTTP/1.1
Content-Type: application/json
Accept-Encoding: gzip, deflate
Content-Length: 57
Host: localhost:8080
Connection: Keep-Alive

{"id":12,"firstName":"Catain","lastName":"Hook","age":10}

Note: Of course you can produce your POST request using any other tool that does the job. The example will work as long as you append the appropriate code in the POST Request body, like you see in the above request. For instance, you could simply write as a String in JSON format and append it to the request.

Download Eclipse Project

This was an JSON Example With RESTEasy+ Jackson. Download the Eclipse Project of this example: RESTEasyJSONExample.zip

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章