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.
Add a com.ibm.json.java.JSONObject class or a com.ibm.json.java.JSONArray class as a parameter to the resource method or as the return type to read or write JSON content.
We can 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.
Results
You 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
- Directory conventions
References in product information to app_server_root, profile_root, and other directories imply specific default directory locations. Become familiar with the conventions in use for WebSphere Application Server.
Related tasks
Use JSON content in JAX-RS application requests and responses