How to set the read and write providers for JSON using JAX-RS in Apache Tomee plus - json

I can return simple text from my Pojo but it fails when I changed to return JSON. I have the correct annotations for produces and consumes in my methods and I checked that the content negotation between Jquery and the server is correct.
It seems to be that the conversion to JSON just fails. I copied the Jackson jars in webapps/tomee/lib. I also tried the lib folder of my application.
The error message when doing a GET:
No message body writer has been found for response class <myClass>
This error is fired by the JAXRSOut Intercepter class
The error when doing a Post is:
No message body reader has been found for request class <myClass>
This error is fired by the JAXRSUtils class
Thanks

I made this work by listing the JAX-RS providers in conf/system.properties file of TomEE. Then I added the jars to TomEE's lib folder. The documentation in the website states that one should drop the jars on webapp/tomee/lib, but that did not work for me.
conf/system.properties
openejb.cxf.jax-rs.providers = org.codehaus.jackson.jaxrs.JacksonJsonProvider, org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
Jars I dropped:
jackson-mapper-asl-1.9.9.jar
jackson-core-asl-1.9.9.jar
jackson-jaxrs-1.9.9

If you use jersey you could try Genson library http://code.google.com/p/genson/.
Latest version 0.92 provides automatic detection of json support in jax-rs web services with jersey.
You should only have to drop the jar and voila! :)

Related

Trouble using json-jackson in camel-blueprint-test

I am trying to test a Camel Blueprint route in camel-blueprint-test. This route can load in karaf and it also worked when using Camel and Spring. At this point I am getting:
org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> Unmarshal[ref:IssRequest] <<< in route: Route(route1)[[From[seda:from_rraa]] -> [process[ref:issPrep... because of Data format 'json-jackson' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1028)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:185)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:841)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:2911)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:2634)
...
Other posts have suggested adding camel-jackson in the pom.xml, but I have that already. Also suggested was loading the feature in the karaf container, but this is when running unit tests in camel-blueprint-test, not in real karaf.
There is a bug in that version, use 2.15.2 or 2.16.0 or wait for 2.15.4

Cannot Produce JSON with Maven quickstart grizzly Archetype

I've put some good hours trying to get my grizzly webserver to produce JSON.
Generated from maven archetype using Intellij, details:
groupId untitled3
artifactId untitled3
version 1.0-SNAPSHOT
archetypeGroupId org.glassfish.jersey.archetypes
archetypeArtifactId jersey-quickstart-grizzly2
archetypeVersion 2.0-m05
All online examples enable JSON using
rc.put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
However, this does not work in jersey 2.x, put method does not exist.
In the application Main class, there is instructions on uncommenting a line of code to get JSON to work. When i uncomment this line of code, the method used does not exist.
public static HttpServer startServer() {
// create a resource config that scans for JAX-RS resources and providers
// in untitled2 package
final ResourceConfig rc = new ResourceConfig().packages("untitled2");
// uncomment the following line if you want to enable
// support for JSON on the service (you also have to uncomment
// dependency on jersey-media-json module in pom.xml)
// --
rc.addModule(org.glassfish.jersey.media.json.JsonJaxbModule);
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
When i try to serve a JSON response from a POJO object i get this error:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class com.example.JsonPost, genericType=class com.example.JsonPost.
I've no idea where to begin to look really. I've googled, plown through documentation and looked through user groups...
Make sure you uncomment the dependency in the POM. Then change the addModule call to this:
rc.addModules(new org.glassfish.jersey.media.json.JsonJaxbModule());
and be sure to include the correct #Produces annotation on your resource:
#Produces(MediaType.APPLICATION_JSON)

Json does not exist in the namespace System

In this tutorial: http://www.asp.net/web-api/videos/getting-started/custom-validation Jon uses
dynamic error = new JsonObject();
with
using System.Json;
I guess it's the JsonObject here: http://msdn.microsoft.com/en-us/library/system.json.jsonobject(v=vs.110).aspx located in:
Namespace: System.Json
Assembly: System.Runtime.Serialization (in System.Runtime.Serialization.dll)
I've added System.Runtime.Serialization a reference but still cannot find System.Json.
Am I reading the Microsoft docs wrong? (I'm using .NET 4.5)
Try this:
PM> Install-Package System.Json -Version 4.0.20126.16343
Per: http://nuget.org/packages/System.Json
It worked!
If you have questions on how to add enter nuget code, please follow the link below:
http://docs.nuget.org/docs/start-here/using-the-package-manager-console
http://www.webcosmoforums.com/asp/32551-type-namespace-name-json-does-not-exist-namespace-system-runtime-serialization.html
Most likely you are missing a reference to System.ServiceModel.Web
Make sure your application is targeting the .Net 4.5 framework in the project properties.
The System.Json objects are only available in 4.5
Edit:
Use Nuget to install system.json : 'Install-Package System.Json'
How to parse JSON without JSON.NET library?
The Json object works only from Controller class and not outside. Even if we refer System.Web.MVC outside controller, we have access only to JsonResult and not to Json as Json object is protected object of JsonResult. Please refer the below documentation which explains that,
http://msdn.microsoft.com/en-us/library/dd504936(v=vs.118).aspx
If you want to use other .Net json serializer, you can use the following:
go to manage nuget package.
search json.net.
click install.
for more details, follow - http://netfx.codeplex.com/
Using System.json will not work for .Net 4 framework. The library is deprecated.
To check it try:
Go Add reference... to project.
On .Net Tab, Search System.json, you will not find any.
That means, it is deprecated.

Unable to find a MessageBodyReader of content-type application/json and type class java.lang.String

I am using RestEasy client with jackson providers and getting the above error
clientside code is:
ClientRequest request = new ClientRequest(url);
request.accept(MediaType.APPLICATION_JSON);
ClientResponse<String> response = request.get(String.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
BufferedReader br =
new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getEntity().getBytes())));
response.getEntity() is throwing ClientResponseFailure exception with the error being
Unable to find a MessageBodyReader of content-type application/json and type class java.lang.String
My server side code is below:
#GET
#Path("/{itemId}")
#Produces(MediaType.APPLICATION_JSON)
public String item(#PathParam("itemId") String itemId) {
//custom code
return gson.toJSON(object);
}
You could try to add the following dependency to your maven pom.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.3.4.Final</version>
</dependency>
The problem actually is that RestEasy is unable to find the Jackson provider. I had to manually register it by the following code:
ResteasyProviderFactory instance=ResteasyProviderFactory.getInstance();
RegisterBuiltin.register(instance);
instance.registerProvider(ResteasyJacksonProvider.class);
Everything is working fine with this. But I am still unhappy with the solution as Resteasy is supposed to scan for the providers and register them automatically.
Client client = ClientBuilder.newBuilder().register(ResteasyJacksonProvider.class).build();
Just adding the line org.jboss.resteasy.plugins.providers.jackson.ResteasyJacksonProvider into META-INF/services/javax.ws.rs.ext.Providers file, solves the problem.
This file is included into resteasy-jackson-providers.jar but same file is also included into another jar, restasy-jaxrs.jar and for an executable jar file, that use both these jars, they are not merged !!
I had a similar problem and I realized that the problem was related with the version of resteasy-jackson-provider. I just moved from 3.0.4.Final to 3.0.5.Final and the problem disappeared.
Additionally I also realized that if I change the third line to the following the result was the expected with no need to change the dependencies.
Response response = request.get(Object.class).toString();
Things that had made work my code were that I added:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>&{resteasy.version}</version>
</dependency>
Beside this I don't know why but it seems that resteasy not initializing providers when client were created, this means that it required to init them manually:
ResteasyProviderFactory instance=ResteasyProviderFactory.getInstance();
RegisterBuiltin.register(instance);
instance.registerProvider(ResteasyJackson2Provider.class);
In general it's enough to run the client.
I don't know the full rationale behind that but we've hit the exact same problem (multiple times :P) and you need to change the MediaType to TEXT_PLAIN.
Or you can also let JAX-RS do the job for you: instead of doing gson.toJSON(object), simply return object and change your method signature to whatever class that is. JAX-RS (RESTEasy in your case) will automatically call Jackson (if it's properly configured) and serialize your object to json. Then on your client side you would request for that same class instead of String and everything should work on its own. I'm not particularly familiar with ClientRequest/Response so it might not work as I said; we use RESTEasy proxy functionality on the client side instead (see ProxyFactory). Nevertheless, JAX-RS/RESTEasy can do json serialize/deserialize automatically on the client side too so there's definetly a way.
If you really want to by-pass goodness of JAX-RS actually doing serialization for you (instead of manually calling GSON), use StreamingOutput (i.e. wrap outputter as StreamingOutput, return that object).

Unable to parse JSON error using Twitterizer TwitterStatus.Show method

Running this code:
var statusResponse = TwitterStatus.Show(tweet.Id);
gives an error message: Unable to parse JSON in the statusResponse object and the ResponseObject comes back as null.
Not sure how to fix this. Any ideas?
I run into the same issue today. It seems that you reference a newer version of Newtonsoft.Json in your project (or maybe an other NuGet package included it).
The problem can be fixed by using the Newtonsoft.Json 4.0.5.0 library that is shipped with the Twitterizer project. It needs to be that exact version.