RestEasy - Jax-rs - Sending custom Object in response body

荒凉一梦 提交于 2019-11-29 10:42:41
gregwhitaker

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:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!