Jersey erro with JSON in Tomcat7 - json

I deployed a rest using Grizzly container and have used the code below to send a JSON object. Everything works very well.
ClientResponse response = wr.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, cliente);
String body = response.getEntity(String.class);
System.out.println("status="+response.getStatus() + "\n" + body);
When I deployed the same rest example in Tomcat 7, this code stopped working showing the following message:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class javax.xml.bind.JAXBElement<crud.Cliente>]: can not instantiate from JSON object (need to add/enable type information?)
I really dont know why....it works on Grizzly embebed container and not work in tomcat?
Anyone know What's going on?
Best regards.

maybe Grizzly uses it's own serializer/deserializer. Try to add an empty constructor to Cliente class:
public Cliente() {
};

Related

Jersey Web Service

I am using Jersey Rest Service. I am getting clients requests in json and getting java object out of it. Everything works fine. However, is there anyway I can get the exact json that was pass from client without even converting to java object.
Issue is json request contents just two parameters and below ObjectMapper converts back to Json but with null values. To ignore, I have to put #JsonInclude(Include.NON_NULL) on each pojo class. If I can get just client json, then it would be good.
ObjectMapper mapper=new ObjectMapper();
String jsonString= mapper.writeValueAsString(body);
Keep the following in your resource method:
#Consumes("application/json")
public Response fn(String payload){} //Notice the payload of type string.
That way the payload will be just a String. I am still not sure why you want it this way, but it should work.

Jersey / Jackson Unsupported Media Type (for XML requests)

I have spent two days on this with no luck. I have a project that uses jersey and jackson. It was working fine with JSON requests and tried to add XML also, after adding a couple of jars, it worked also with XML.
The problem was that for requests with no parameters (neither JSON nor XML), the API was retrieving XML instead JSON (we want JSON by default).
My code for requests looks like this:
#POST
#Produces({"application/json", "application/xml"})
#Consumes({"application/json", "application/xml"})
public TokenResponse authenticateUser(Credentials credentials) {//code here}
In another post a saw that this is a Jetty bug that is resolved in version 2.16, so I decided to migrate to 2.51.1 with no luck. The JSON request works fine, but when I send the xml post (with postman) the server returns an "Unsupported Media Type" error.
I have also tried with version jersey 2.17 because it works with the same jackson libraries than 2.7 and the result is the same than before.
I am not using maven so here it is a copy of the libraries I have used for the three cases:
1.- JSON and XML works but XML is always returned by default:
2.- JSON works but XML requests returns Unsupported Media Type
3.- JSON works but XML requests returns Unsupported Media Type
Thank you in advance
Finally, instead of updating the libraries I have decided to use the version I had already and add the solution below to #Produces annotation
How to set to default to json instead of xml in jersey?
Setting a qs factor to each media type as mentioned in this answer should work. It can take values between 0 (undesirable) and 1 (highly desirable):
#Produces({ "application/json; qs=1", "application/xml; qs=.5" })
If you don't want to change every single #Produces annotation, you can use a filter to add the Accept: application/json header if it's not present.
#Provider
#PreMatching
public class DefaultAcceptHeaderFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
MultivaluedMap<String, String> headers = requestContext.getHeaders();
if (!headers.containsKey(HttpHeaders.ACCEPT)) {
headers.putSingle(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
}
}
}
It will ensure that your resource methods will produce JSON even when the Accept header is not sent by the client.

Issue while Sending JSON Request

I am facing an issue when i am sending a REST request in JSON format.Some of the parameters are getting missed when it invokes the service.However it works fine when i send the request in xml format.The issue which i am geting throws below error:
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "create_session_param"
The object mapper class looks as below:
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);
JaxbAnnotationModule module = new JaxbAnnotationModule();
// maintain JAXB annotation support
objectMapper.registerModule(module);
Can someone please help me to resolve this?
Thanks.
You only have WRAP_ROOT_VALUE which is for serialization. Remember serialization is POJO to JSON. The SerializationFeature.WRAP_ROOT_VALUE is the one that actually adds the "create_session_param" when creating the JSON.
We need JSON to POJO, which is deserialization, which has its own feature set. In this case, we need a feature to unwrap the root value in the JSON. For that there is
DeserializationFeature.UNWRAP_ROOT_VALUE
So do
mapper.configure(DeserializationFeature UNWRAP_ROOT_VALUE, true);

Moxy, JSON and Jersey 2.0 does not deserialize plain String array

In my current setup I use Jersey 2.0 with MOXy as discribed in jersey docs. I rely completely on the
“Auto-Discoverable Features”, so I do not use any extra configuration or JAXB annotation.
My task is to deserialize an array of strings on the server side. The client is sending the JSON message:
["foo","bar"]
And on the server side the following method header should deserialize it:
#POST
#Path("/stringArray")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response stringArray(List<String> stringList) {
...
}
Problem:
The content of stringList is {null,null}, so the amount of elements is always correct, but the strings are set to null.
The same with a small wrapper class is working. Here the class:
public static class Data {
public List<String> stringList;
}
Changing methode signature to stringArray(Data data) and changing the JSON message to:
{"stringList": ["foo","bar"]}
What is the difference between the two approaches and how can I get the plain string array working?
Update:
The described problem is fixed by answer from #Blaise. But the closely related problem of serializing a List of POJOs does still not work. Message:
[org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:
MessageBodyWriter not found for media type=application/json,
type=class java.util.ArrayList, genericType=class
java.util.ArrayList.]
The only solution I found is again using a small wrapper class containing the List...
The issue you are seeing is due to a bug in EclipseLink JAXB (MOXy):
http://bugs.eclipse.org/412336
This bug has been fixed in the EclipseLink 2.5.1 and 2.6.0 streams. You can download a nightly build starting July 5, 2013 from the following link:
http://www.eclipse.org/eclipselink/downloads/nightly.php

How can I serialize Exceptions using Json.NET on WinRT?

This works fine on classic .NET:
string json = JsonConvert.SerializeObject(new Exception("Test"));
But it fails on WinRT (RP) with:
Error getting value from 'TargetSite' on 'System.Exception'.
The API 'System.Exception.get_TargetSite()' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information.
EDIT:
I also need to transfer the Exception over the wire and deserialize it on the back end side.
Anyone has any workarounds?