+

Search Tips   |   Advanced Search

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. We do not need to bundle any additional libraries.


Tasks

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.

Use JSON4J types as request entity parameters or we 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.

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


Example

The following example illustrates a JSONArray class 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;
    }
}


Subtopics

  • Use JSON content in JAX-RS application requests and responses