I have been trying to get JSON
data but it seems I am using the wrong syntax. What syntax is appropriate? This is my code
@Path("/jsondata")
@POST
@Consumes("application/json")
@Produces("application/json")
public JSONObject personal(@JSONParam("")JSONObject json) throws JSONException{
String name = json.getString("name");
String age = json.getString("age");
String msg = "You entered two things";
String doc = "{\"name\":\""+name+"\",\"age\":\""+age+"\",\"msg\":\""+msg+"\"}";
JSONObject outJson = new JSONObject(doc);
return outJson;
}
Am getting error on the fifth line at @JSONParam
. What should i do. And how do I get the name and age from the json
Well actually any JAX-RS implementation should be able to support JSON natively such that you are supposed to manipulate POJO instead of JSON object.
@Consumes("application/json")
, the framework knows that the input data is in JSON format so it will deserialize it into the expected Java Object Type. @Produces("application/json")
, the framework knows that the result is in JSON format so it will serialize the returned Java Object in JSON format. Here is an example from this article
@Path("/json/metallica")
public class JSONService {
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
}
As you can see getTrackInJSON
is annotated with @Produces(MediaType.APPLICATION_JSON)
such that it can return the object Track
, the framework will convert it into JSON format.
As you can see createTrackInJSON
is annotated with @Consumes(MediaType.APPLICATION_JSON)
and has one parameter which is of type Track
such that the framework will parse the input data to provide directly an instance of Track
as parameter to the method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.