I am writing a web service the first time. I created a RESTful web service based on Jersey. And I want to produce JSON. What do I need to do to generate the correct JSON type of my web service?
Here's one of my methods:
@GET
@Path("/friends")
@Produces("application/json")
public String getFriends() {
return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
}
Is it sufficient that I simply point out annotation @Produces("application/json")
for my method? Then this method may return any type of object? Or only String? Do I need additional processing or transformation of these objects?
Please help me as a beginner to deal with these issues. Thanks in advance!
This question is related to
java
json
web-services
rest
jersey
@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
return jsonObject;
}
You could use a package like org.json http://www.json.org/java/
Because you will need to use JSONObjects more often.
There you can easily create JSONObjects and put some values in it:
JSONObject json = new JSONObject();
JSONArray array=new JSONArray();
array.put("1");
array.put("2");
json.put("friends", array);
System.out.println(json.toString(2));
{"friends": [
"1",
"2"
]}
edit This has the advantage that you can build your responses in different layers and return them as an object
@GET
@Path("/friends")
@Produces(MediaType.APPLICATION_JSON)
public String getFriends() {
// here you can return any bean also it will automatically convert into json
return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
}
Use this annotation
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
Source: Stackoverflow.com