Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the Jersey JSON POJO support?

I have an object that I'd like to serve in JSON as a RESTful resource. I have Jersey's JSON POJO support turned on like so (in web.xml):

<servlet>       <servlet-name>Jersey Web Application</servlet-name>       <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>     <init-param>         <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>         <param-value>true</param-value>     </init-param>      <load-on-startup>1</load-on-startup>   </servlet>   

But when I try to access the resource, I get this exception:

SEVERE: A message body writer for Java type, class com.example.MyDto, and MIME media type, application/json, was not found SEVERE: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException ... 

The class that I'm trying to serve isn't complicated, all it's got are some public final fields and a constructor that sets all of them. The fields are all strings, primitives, classes similar to this one, or Lists thereof (I've tried using plain Lists instead of generic List<T>s, to no avail). Does anyone know what gives? Thanks!

Java EE 6

Jersey 1.1.5

GlassFish 3.0.1

like image 793
Nick Avatar asked Mar 01 '11 23:03

Nick


People also ask

How do I get JSON request in Jersey?

if you want your json as an Vote object then simple use @RequestBody Vote body in your mathod argument , Spring will automatically convert your Json in Vote Object.

Does Jersey use Jackson?

Jersey uses Jackson internally to convert Java objects to JSON and vice versa.


1 Answers

You can use @XmlRootElement if you want to use JAXB annotations (see other answers).

However, if you prefer pure POJO mapping, you must do the following (Unfortunately it isn't written in docs):

  1. Add jackson*.jar to your classpath (As stated by @Vitali Bichov);
  2. In web.xml, if you're using com.sun.jersey.config.property.packages init parameter, add org.codehaus.jackson.jaxrs to the list. This will include JSON providers in the scan list of Jersey.
like image 60
gamliela Avatar answered Oct 17 '22 04:10

gamliela