RestEasy - Jax-rs - sending a custom object to the response body

How to send your custom object in response. I just want the values ​​to be printed from my object.

Suppose I have an object of type Person . I am trying to send the body of a REST response this way.

  ResponseBuilder response = Response.ok().entity(personObj); return response.build(); 

But I get a 500 error. Tried this too:

  ResponseBuilder response = Response.status(Status.OK).entity(personObj); return response.build(); 

The same mistakes.

Tried setting the content type as text/xml . Do not use. What am I missing here? I tried to search. But not many examples, especially with custom objects;

It returns a penalty if I just pass the string to the entity() method.

+6
source share
1 answer

To return data from the Restaasy resource method, you need to do a few things depending on what you are trying to return.

  • You need to annotate your resource method using the @Produces annotation to tell Resteasy what the return type should be.

    For example, the following method returns XML and JSON depending on what the client requests in its Accept header.

 @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response foo() { PersonObj obj = new PersonObj(); //Do something... return Response.ok().entity(obj).build(); } 

Restaasy supports sorting of the following data types by default:

enter image description here

If the data types you want to support are in this table, then it means that they are supported by JAXB, and all you have to do is annotate your PersonObj class with JAXB annotations to tell you how the marshall and unmarshall object are.

 @XmlRootElement @XmlType(propOrder = {"firstName", "lastName"}) public class PersonObj { private String firstName; private String lastName; //Getters and Setters Removed For Brevity } 

What if your content type is not supported out of the box?

If you have a custom content type that you want to customize, you need to create a MessageBodyWriter implementation that tells Resteasy how to set up the token.

 Provider @Produces({"application/x-mycustomtype"}) public class MyCustomTypeMessageBodyWriter implements MessageBodyWriter { } 

Just implement the interface and register it like any other provider.

If you want to read a custom content type, you need to implement a custom MessageBodyReader to process the incoming type and add it to the @Consumes annotation @Consumes to your receiving method.

+12
source

Source: https://habr.com/ru/post/948969/


All Articles