how to store JSON into POJO using Jackson - json

I am developing a module where i am using rest service to get data. i am not getting how to store JSON using Jackson and store it which has Queryparam also. Any help is really appreciated as I am new to this.I am trying to do server side filtering in extjs infinte grid which is sending the below request to rest service.
When the page load first time, it sends:
http://myhost/mycontext/rest/populateGrid?_dc=9999999999999&page=1&start=0&limit=500
When you select filter on name and place, it sends:
http://myhost/mycontext/rest/populateGrid?_dc=9999999999999&filter=[{"type":"string","value":"Tom","field":"name"},{"type":"string","value":"London","field":"Location"}]&page=1&start=0&limit=500
I am trying to save this in POJO and then sending this to database to retrieve data. For this on rest side I have written something like this:
#Provider
#Path("/rest")
public interface restAccessPoint {
#GET
#Path("/populateGrid")
#Produces({MediaType.APPLICATION_JSON})
public Response getallGridData(FilterJsonToJava filterparam,#QueryParam("page") String page,#QueryParam("start") String start,#QueryParam("limit") String limit);
}
public class FilterJsonToJava {
#JsonProperty(value ="filter")
private List<Filter> data;
.. getter and setter below
}
public class Filter {
#JsonProperty("type")
private String type;
#JsonProperty("value")
private String value;
#JsonProperty("field")
private String field;
...getter and setters below
}
I am getting the below error:
The following warnings have been detected with resource and/or provider classes: WARNING: A HTTP GET method, public abstract javax.ws.rs.core.Response com.xx.xx.xx.xxxxx (com.xx.xx.xx.xx.json.FilterJsonToJava ,java.lang.String,java.lang.String,java.lang.String), should not consume any entity.
com.xx.xx.xx.xx.json.FilterJsonToJava, and Java type class com.xx.xx.xx.FilterJsonToJava, and MIME media type application/octet-stream was not found
[11/6/13 17:46:54:065] 0000001c ContainerRequ E The registered message body readers compatible with the MIME media type are:
application/octet-stream
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider com.sun.jersey.core.impl.provider.entity.FileProvider com.sun.jersey.core.impl.provider.entity.InputStreamProvider com.sun.jersey.core.impl.provider.entity.DataSourceProvider com.sun.jersey.core.impl.provider.entity.RenderedImageProvider */* -> com.sun.jersey.core.impl.provider.entity.FormProvider ...

You should try to do it this way:
Response getallGridData(#QueryParam("filter") String filterparam, ...) {
ObjectMapper mapper = new ObjectMapper();
Filter yourObject = mapper.readValue(filterparam, Filter.class);
}
This is the way, because your payload is in the query parameter. The object injected as it is with POST requests when there is a payload.

Related

Unsupported Media Type Error in AJAX-Spring

I am trying to pass POST data from my jsp with jquery-ajax to my Spring-MVC controller function. The data is passed fine and I can print the JSON data when I use a String object to receive the RequestBody. But when I employ a DTO which has a List variable declared with its own objects the controller returns a '415 Unsupported Media Type Error' with the following statement,
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
below given is the DTO class
public class anyClassDTO{
private String name;
private List<anyClassDTO> subList = new ArrayList<anyClassDTO>();
//getters and setters here
}
Now, here is the controller function
#RequestMapping(headers ={"Accept=application/json"}, value = "urlFromJsp", method = RequestMethod.POST)
public #ResponseBody
String addData (HttpServletRequest request,
#RequestBody List<anyClassDTO> dtoObject,
Model model)
{
return "{\"value\":\"true\"}";
}
Is it not possible for a list of objects to be received from the jsp page to a controller via AJAX?
Here is a set of sample data being passed from the jsp
[{"name":"module1","subList":[{"name":"chapter1","subList":[{"name":"subchapter1","subList":null}]}]},{"name":"module2","subList":[{"name":"chapter1","subList":[{"name":"subchapter1","subList":null}]}]}]
Make sure your AJAX request sets the request's Content-Type to application/json.
Spring typically uses a MappingJacksonHttpMessageConverter to convert the request body when you specify #RequestBody. This HttpMessageConverter only supports application/*+json type content types, so you have to make sure your request contains it.
Well, we could make it work as it is by adding a little more detail. Instead of receiving the #ResponseBody as a List object I created another DTO which holds a List object of the original DTO. So the second DTO is basically a dummy which receives the data from AJAX as a single object.
Like I have said in the question I have a DTO as follows
public class AnyClassDTO{
private String name;
private List<anyClassDTO> subList = new ArrayList<anyClassDTO>();
//getters and setters here
}
I created another DTO which holds a List of the above DTO
public class DummyDTO{
private List<AnyClassDTO> dummyObj;
//getters and setters here
}
Then in the controller I changed the function to
#RequestMapping(headers ={"Accept=application/json"}, value = "urlFromJsp", method = RequestMethod.POST)
public #ResponseBody
String addData (HttpServletRequest request,
#RequestBody DummyDTO dummyDTOObj,
Model model)
{
return "{\"value\":\"true\"}";
}
Earlier if I was sending a list directly from AJAX, now I am sending a stringified litteral with a variable which holds the whole data.
And it works like a charm!

JAX-RS / Jersey ".get(Integer.class)" and single JSON primitive (Integer) values?

I have a JAX-RS WebService with the following method:
#Path("/myrest")
public class MyRestResource {
...
#GET
#Path("/getInteger")
#Produces(APPLICATION_JSON)
public Integer getInteger() {
return 42;
}
When accessed using this snipped:
#Test
public void testGetPrimitiveWrapers() throws IOException {
// this works:
assertEquals(new Integer(42), new ObjectMapper().readValue("42", Integer.class));
// that fails:
assertEquals(new Integer(42), resource().path("/myrest/getInteger").get(Integer.class));
}
I get the following exception:
com.sun.jersey.api.client.ClientResponse getEntity
SEVERE: A message body reader for Java class java.lang.Integer, and Java type class java.lang.Integer, and MIME media type application/json was not found
com.sun.jersey.api.client.ClientResponse getEntity
SEVERE: The registered message body readers compatible with the MIME media type are: application/json
...
The problem is just with returning single primitive values (int/boolean) or their wrapper classes. Returning other POJO classes is not the problemen so I guess all the answers regarding JSONConfiguration.FEATURE_POJO_MAPPING and JAXB annotations do not apply here.
Or which annotation should I use to describe the return type if I don't have access to its
class source?
Using ngrep I can verify that just the String "42" is returned by the webservice. Thats a valid JSON "value" but not a valid JSON "text" according to the spec. So is my problem on the client or the server side?
I tried activating JSONConfiguration natural/badgerfish according to http://tugdualgrall.blogspot.de/2011/09/jax-rs-jersey-and-single-element-arrays.html but with no success (ngrep still shows just "42"). Would that be the right path?
Any ideas are appreciated!
This is a recognized bug in Jackson, which has been touted (incorrectly in my opinion) as a feature. Why do I consider it a bug? Because while serialization works, deserialization definitely does not.
In any case, valid JSON cannot be generated from your current return type, so I would recommend creating a wrapper class:
class Result<T> {
private T data;
// constructors, getters, setters
}
#GET
#Path("/getInteger")
#Produces(APPLICATION_JSON)
public Result<Integer> getInteger() {
return new Result<Integer)(42);
}
Alternatively, you can elect to wrap root values, which will automatically encapsulate your data in a top level JSON object, keyed by the objects simple type name - but note that if this option is used that all generated JSON will be wrapped (not just for primitives):
final ObjectMapper mapper = new ObjectMapper()
.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
final String serializedJson = mapper.writeValueAsString(42);
final Integer deserializedVal = mapper.readValue(serializedJson,
Integer.class);
System.out.println(serializedJson);
System.out.println("Deserialized Value: " + deserializedVal);
Output:
{"Integer":42}
Deserialized Value: 42
See this answer for details on how to retrieve and configure your ObjectMapper instance in a JAX-RS environment.

Is it possible to get jersey to read json variables our of a request body without using a bean?

In jersey a Java bean can be auto-deserialized from within a request body but what if I want to read a parameter without creating a special type. Is it possible to do this using annotations.
My current code is:
public class RequestData {
String param;
}
...
public Response readData(RequestData data) {
data.getParam();
...
}
I want it to be something like:
public Response readData(#RequestParam("param") String param) {
...
}
If its not already clear the input JSON is:
{
"param":"some value"
}
The type of your input JSON is Map<String, String> so if you want to have undifferentiated input you could use that as your request parameter and read the values that you require.
Note that #RequestParam looks at the request parameters and not the body, so it's a different beast.
You do this by letting Jersey pass you String as is (as per annotations), and then data-bind it using Jackson ObjectMapper (thing Jersey uses internally for JSON binding):
Map<String,Object> map = objectMapper.readValue(param, Map.class);
to get access to ObjectMapper, you can use JAX-RS injection annotation (#Context I think?) in the resource class:
#Context
private ObjectMapper objectMapper;

Exception with REST implementation with jersey

I am building a REST service with jersey and I am stuck with a weird exception.
I want to hit a REST uri similar to:
http://localhost:9889/rest/Users/{userid}
the content to be sent with the request is in JSON similar to:
{
"attr1":"name",
"attr2":"age"
}
The endpoint url code is as shwon below:
#Path("/rest/Users")
class Users
{
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/{userId}")
#Consumes(MediaType.APPLICATION_JSON)
public String getUserInfoQuery(
QueryDoc reqJSON,
#PathParam("userId") String userId,
#HeaderParam("Session-Token") String sessionId,
#HeaderParam("Authorization") String authToken)
)
{
.
.
.
.
}
}
And QueryDoc resource looks like this:
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class QueryDoc
{
#XmlElement(name = "attr1")
private String attr1;
#XmlElement(name = "attr2")
private String attr2;
//getters and setters
.
.
.
.
}
When I am starting the server, an exception is thrown
com.sun.jersey.api.container.ContainerException: Fatal issues found at
class com.test.Users. See logs for more details.
at com.sun.jersey.server.impl.application.WebApplicationImpl.newResourceClass(WebApplicationIm....
I could find this exception here http://www.skybert.net/java/jersey/
and as mentioned in this link..the reason is
public String getUserInfoQuery(
QueryDoc reqJSON,
reqJSON is not being annotated. If I annotate it with some annotation the exception is not thrown when server is started but in this case url response is meaningless. If i remove this parameter the url works but it doesn't consume the request JSON.
How can I make it work where I want to consume JSON content of the request as well as HeaderParams and PathParams
Is your getUserInfoQuery() method annotated with #GET annotation? If so, it is mapped to HTTP GET request. You cannot send entity in HTTP GET, so the unannotated parameter does not make sense (as Jersey maps entity to the unannotated param, but as said, in case of GET there is no entity).
Change your method getUserInfoQuery() to #PUT. In the QueryDoc class remove all annotations except #XmlRootElement. Since the attribute name you pass in the request body is same as the those in QueryDoc #XmlElement is not required. Moreover #XmlElement should be given to ge getter method.This is a good article on ReST with Jersey.
Try this:
I had the same exception with no additional details on Jersey's 'newResourceClass' method;
after hours of debugging, I realized it happened due to ambiguous URIs.
Check your URIs and eliminate any possible duplicates, such as this one:
#Path("/users")
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<String> getUsers() {
...
}
#Path("/users") // BAD
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getUserById(#QueryParam("userId") String userId) {
...
}

Consuming JSON object in Jersey service

I've been Googling my butt off trying to find out how to do this: I have a Jersey REST service. The request that invokes the REST service contains a JSON object. My question is, from the Jersey POST method implementation, how can I get access to the JSON that is in the body of the HTTP request?
Any tips, tricks, pointers to sample code would be greatly appreciated.
Thanks...
--Steve
As already suggested, changing the #Consumes Content-Type to text/plain will work, but it doesn't seem right from an REST API point of view.
Imagine your customer having to POST JSON to your API but needing to specify the Content-Type header as text/plain. It's not clean in my opinion. In simple terms, if your API accepts JSON then the request header should specify Content-Type: application/json.
In order to accept JSON but serialize it into a String object rather than a POJO you can implement a custom MessageBodyReader. Doing it this way is just as easy, and you won't have to compromise on your API spec.
It's worth reading the docs for MessageBodyReader so you know exactly how it works. This is how I did it:
Step 1. Implement a custom MessageBodyReader
#Provider
#Consumes("application/json")
public class CustomJsonReader<T> implements MessageBodyReader<T> {
#Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations,MediaType mediaType) {
return true;
}
#Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
/* Copy the input stream to String. Do this however you like.
* Here I use Commons IOUtils.
*/
StringWriter writer = new StringWriter();
IOUtils.copy(entityStream, writer, "UTF-8");
String json = writer.toString();
/* if the input stream is expected to be deserialized into a String,
* then just cast it
*/
if (String.class == genericType)
return type.cast(json);
/* Otherwise, deserialize the JSON into a POJO type.
* You can use whatever JSON library you want, here's
* a simply example using GSON.
*/
return new Gson().fromJson(json, genericType);
}
}
The basic concept above is to check if the input stream is expected to be converted to a String (specified by Type genericType). If so, then simply cast the JSON into the specified type (which will be a String). If the expected type is some sort of POJO, then use a JSON library (e.g. Jackson or GSON) to deserialize it to a POJO.
Step 2. Bind your MessageBodyReader
This depends on what framework you're using. I find that Guice and Jersey work well together. Here's how I bind my MessageBodyReader in Guice:
In my JerseyServletModule I bind the reader like so --
bind(CustomJsonReader.class).in(Scopes.SINGLETON);
The above CustomJsonReader will deserialize JSON payloads into POJOs as well as, if you simply want the raw JSON, String objects.
The benefit of doing it this way is that it will accept Content-Type: application/json. In other words, your request handler can be set to consume JSON, which seems proper:
#POST
#Path("/stuff")
#Consumes("application/json")
public void doStuff(String json) {
/* do stuff with the json string */
return;
}
Jersey supports low-level access to the parsed JSONObject using the Jettison types JSONObject and JSONArray.
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.8</version>
</dependency>
For example:
{
"A": "a value",
"B": "another value"
}
#POST
#Path("/")
#Consumes(MediaType.APPLICATION_JSON)
public void doStuff(JSONObject json) {
/* extract data values using DOM-like API */
String a = json.optString("A");
Strong b = json.optString("B");
return;
}
See the Jersey documentation for more examples.
I'm not sure how you would get at the JSON string itself, but you can certainly get at the data it contains as follows:
Define a JAXB annotated Java class (C) that has the same structure as the JSON object that is being passed on the request.
e.g. for a JSON message:
{
"A": "a value",
"B": "another value"
}
Use something like:
#XmlAccessorType(XmlAccessType.FIELD)
public class C
{
public String A;
public String B;
}
Then, you can define a method in your resource class with a parameter of type C. When Jersey invokes your method, the JAXB object will be created based on the POSTed JSON object.
#Path("/resource")
public class MyResource
{
#POST
public put(C c)
{
doSomething(c.A);
doSomethingElse(c.B);
}
}
This gives you access to the raw post.
#POST
#Path("/")
#Consumes("text/plain")
#Produces(MediaType.APPLICATION_JSON)
public String processRequset(String pData) {
// do some stuff,
return someJson;
}
Submit/POST the form/HTTP.POST with a parameter with the JSON as the value.
#QueryParam jsonString
public desolveJson(jsonString)
Some of the answers say a service function must use consumes=text/plain but my Jersey version is fine with application/json type. Jackson and Jersey version is
jackson-core=2.6.1, jersey-common=2.21.0.
#POST
#Path("/{name}/update/{code}")
#Consumes({ "application/json;charset=UTF-8" })
#Produces({ "application/json;charset=UTF-8" })
public Response doUpdate(#Context HttpServletRequest req, #PathParam("name") String name,
#PathParam("code") String code, String reqBody) {
System.out.println(reqBody);
StreamingOutput stream = new StreamingOutput() {
#Override public void write(OutputStream os) throws IOException, WebApplicationException {
..my fanzy custom json stream writer..
}
};
CacheControl cc = new CacheControl();
cc.setNoCache(true);
return Response.ok().type("application/json;charset=UTF-8")
.cacheControl(cc).entity(stream).build();
}
Client submits application/json request with a json request body. Servlet code may parse string to JSON object or save as-is to a database.
SIMPLE SOLUTION:
If you just have a simple JSON object coming to the server and you DON'T want to create a new POJO (java class) then just do this.
The JSON I am sending to the server
{
"studentId" : 1
}
The server code:
//just to show you the full name of JsonObject class
import javax.json.JsonObject;
#Path("/")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response deleteStudent(JsonObject json) {
//Get studentId from body <-------- The relevant part
int studentId = json.getInt("studentId");
//Return something if necessery
return Response.ok().build();
}