Wednesday, August 14, 2013

Java WebService Tutorial - Part 13 ( XML & JSON )


Producing XML and JSON:

In the previous section we have seen how to access Parameters from URL and what are useful classes we can use in our REST Services. In this section we will see how to Produce different Responses such as XML and JSON in REST.

So far in our all example, we have used GET and access directly from the Browser URL.What if some one wants to POST data , in this case i need to used POST Method, let see the following example here.

    @POST
    @Path("/Postme")
    @Produces("text/plain")
    public Response getData(@FormParam("user")String user)
    {
        return Response.ok(user).build();
    }

I cannot go directly in to the Browser and hit the URL with the Path .../Postme it will give me an error saying Method not allowed, we cannot directly do that, either we need a form to Post these changes and we need to write a client class to access this service. How to write a Client to access REST Service will be cover in later Parts. Now we will see how to do this by using a Html Form Submission.

Ex:

<form method="post" action="/....../Postme">
User :<input type="text" name="user">
<input type="submit">
</form>

When the submit button is pressed the "/Postme"Path 's respective Method get's invoked and it takes the parameter "user" which is a textfield inside the form tag ,and return the Response as the value entered in the html textfield.

As , for Producing JSON and XML we can use get or post it depend upon the criteria, now for our understanding , i am using GET to Produce  JSON and XML Data and display it to the User.

1. XML :

XML can be produce in two ways , either using the JAXB if you don't know JAXB , no need to Panic it just an API Provided by J2EE for quickly forming XML ,Parsing XML and Producing XML.

It takes some little Annotations that's it it wont take much time to understand the basics of JAXB.
Jersey , automatically does the XML /JSON Conversion, while returning response.

Another way to produce the XML is by returning as String in the Response, it is not the best way , but it can also produce XML Output.

EX:
    @Path("/check/{username}")
    @GET
    @Produces("text/xml")
    public String getText(@PathParam("username")String username) {
     return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>   <username>"+username+"</username></root>";
    }

This code will Produce the output as String in the XML Format.

 If you access from URL:  ....../check/John

Output :<root><username>John</username></root>

Using JAXB Style:

Create a Class called "Student".

package test;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement // This does everthing for Creating XML .
public class student {
private int rollno;
 private String name;
  public int getRollno() {
        return rollno;
    }
    public void setRollno(int rollno) {
        this.rollno = rollno;
    }
public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  
}

Inside the REST Service Class:

    @Path("/getXML")
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public student getXML()
    {
        student s=new student();
        s.setName("Ayaz");
        s.setRollno(1440);
        return s;
    }
Deploy the Service & Access this Method ....../getXML  will return the following Output:

XML Output :
<student><name>Ayaz</name><rollno>1440</rollno></student>

Note : Just By changing MediaType.APPLICATION_XML to
MediaType.APPLICATION_JSON in the @Produces Annotation of the Method getXML will give the following JSON Output 

JSON Output :
{"rollno":1440,"name":"Ayaz"}

2. JSON:

We have already seen the how to produce JSON output using JAXB, Now we will look at how we can do it manually using the JSON classes provided by the Jackson framework which comes along with the Jersey.
It can be done by specifying the following in the web.xml file:
          <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
              </init-param>
This enables the Jackson framework which comes along with the Jersey.Jackson used to provide the libraries to use for accessing and producing JSON.

Ex:
    @Path(“/Mydata”)
    @GET
    @Produces("application/json")
    public Response getData() throws JSONException
    {
        JSONObject jSONObject=new JSONObject();
        JSONArray array=new JSONArray();
        
       for(int i=0;i<5;i++)
       {
        jSONObject.put("name"+i, i);
          
       }
        array.put(jSONObject);
        String h=array.toString();
        Response r=null;
        r=Response.ok(h).build();
        return r;
    }

Output:
[{"name0":0,"name1":1,"name2":2,"name3":3,"name4":4}]

That's all folks , in the next section we will see how to write a REST client.

Thanks for Reading... 
Please provide your valuable comments & suggestion.


<<Prev                           Index                             Next >>

------------------------------------------------------------------------------------------ 







Technology Blogs
blogs

7 comments: