Network Deployment (Distributed operating systems), v8.0 > End-to-end paths > Web services - RESTful services > Use JSON content in JAX-RS application requests and responses > 4. Implement a resource method using JSON content for a request and response entity.


Implement a resource method using IBM JSON4J

RESTful services can consume and produce content using the JavaScript Object Notation (JSON) format.

IBM JSON4J types are supported entity types. The JSON4J library is included in the runtime environment of this product. You do not need to bundle any additional libraries.


Procedure

Add a com.ibm.json.java.JSONObject class or a com.ibm.json.java.JSONArray class as a parameter to your resource method or as your return type to read or write JSON content.

We can use JSON4J types as request entity parameters or you can return JSON4J types to produce JSON messages; for example:

@POST
public com.ibm.json.java.JSONObject createGreetingForPerson(com.ibm.json.java.JSONObject person) {
    String name = (String)person.get("name");
    com.ibm.json.java.JSONObject greetingInJSONObj = new JSONObject();    greetingInJSONObj.put("greeting", "Hello " + name);
    return greetingInJSONObj;
}

JSON content, like the following code snippet, { "name" : "Bob Smith" }, is sent in the request and is stored in the JSONObject person.

JSON content, like the following code snippet, { "greeting" : "Hello Bob Smith" }, is returned in the response.


Results

You have implemented JSON4J types to process JSON requests and message types.


Example

The following example illustrates a JSONArray class that is used to return a list of people and a method used to process a greeting for a person.

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;


@Path("/people")
public class JSON4JResource {

    @GET
    public JSONArray getPersonArray() {
        JSONArray personArray = new JSONArray();
 
        JSONObject firstPerson = new JSONObject();
        firstPerson.put("name", "John Doe");
        personArray.add(firstPerson);
 
        JSONObject secondPerson = new JSONObject();
        secondPerson.put("name", "Fred Thompson");
        personArray.add(secondPerson);
 
        return personArray;
    }

    @Path("/greet")
    @POST
    public JSONObject createGreetingForPerson(JSONObject person) {
        String name = (String)person.get("name");
        JSONObject greetingInJSONObj = new JSONObject();
        greetingInJSONObj.put("greeting", "Hello " + name);
        return greetingInJSONObj;
    }
}

Use JSON content in JAX-RS application requests and responses

+

Search Tips   |   Advanced Search