I donβt know which JSON Serializer you are using, but most likely it will be Jettison or Jackson . As far as I know, they do not support conversion of an org.json.JSONObject instance directly. A more common way is to simply use custom Java Beans:
public class Foo implements Serializable { private String platform; // getters + setters } @POST @Path("/{department}/{team}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response handleJson(Foo foo, @PathParam("department") String department, @PathParam("team") String team) { ... myObj.setPlatform(foo.getPlatform()); ... }
Foo should be annotated @XmlRootElement if you are using Jettison.
If you do not want to create a custom Bean for each object that you expect, you can use Object , Map or String as a parameter and serialize it yourself:
@POST @Path("/{department}/{team}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response handleJson(String json, @PathParam("department") String department, @PathParam("team") String team) { ... JSONObject jsonObject = new JSONObject(json); myObj.setPlatform(json.optString("platform")); ... }
The latter solution implements MessageBodyReader , which handles a JSONObject . A simple example:
@Provider public class JsonObjectReader implements MessageBodyReader<JSONObject> { @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == JSONObject.class && MediaType.APPLICATION_JSON_TYPE.equals(mediaType); } @Override public JSONObject readFrom(Class<JSONObject> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { return new JSONObject(IOUtils.toString(entityStream)); } }
source share