Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I send my custom object in a response. I just want the values printed from my object.

Lets say I have an object of type Person. I am trying to send in REST response body like this.

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

But I get 500 error. Tried this one too:

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

Same error.

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

It returns fine, if I just pass a string to entity() method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
396 views
Welcome To Ask or Share your Answers For Others

1 Answer

In order to return data from a Resteasy resource method you need to do several things depending on what you are trying to return.

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

    For example, the method below returns XML and JSON depending on what the client asks for in their 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();
}

Resteasy supports marshalling the following datatypes by default:

enter image description here

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

@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 would like to marshall then you need to create a MessageBodyWriter implementation that will tell Resteasy how to marshall the type.

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

}

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

If you would like to read a custom content-type then you need to implement a custom MessageBodyReader to handle the incoming type and add it to the @Consumes annotation on your receiving method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...