RESTful services can consume and produce content using the JavaScript™ Object Notation (JSON) format.
To use JSON4J types as supported entity types, you must add the JSON4J library in the classpath. Then, you are ready to use the JSONObject and the JSONArray classes from the JSON4J library as types to represent request and response message bodies.
The JSON4J library is included in the following Feature Pack for Web 2.0 Feature Pack directory: app_server_root/web2fep/optionalLibraries/JSON4J. Package the JSON4J library with the rest of the IBM® implementation of JAX-RS libraries in your Web application that are located either in the WEB-INF/lib folder or in a shared library.
@POST public JSONObject createGreetingForPerson(JSONObject person) { String name = (String)person.get("name"); 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.
You have implemented JSON4J types to process JSON requests and message types.
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; } }
In this information ... | IBM Redbooks, demos, education, and more(Index) |