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.
@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.
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) |