After spending a couple of days trying to get JAXB and JSON working with a
JAX-RS service I found that the following was required. It wasn't clear to me
from the documentation or samples that explicit declarations of the JAXB
objects in the service bean configuration was required. My initial assumption
was that there was a default JSONProvider instance that didn't require
configuration, and that any object with the @XmlRootElement annotation could be
marshaled.
The following is the correct method for configuring a JAX-RS service using JSON
as the communication protocol?
Web resource interface:
@Path("users")
public interface RestUserService {
@GET
@Path("/{name}")
@Consumes("application/json")
@Produces("application/json")
public Response findUser(@PathParam("name") String name);
@POST
@Consumes("application/json")
@Produces("application/json")
public Response create(User user);
}
Spring bean definition:
<!-- This provider is required when Web resources are using JSON as the
protocol -->
<bean id="jsonProvider"
class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
<property name="singleJaxbContext" value="true" />
<property name="jaxbElementClassNames">
<list>
<value>com.thomsonreuters.services.userservice._2012_02_01.User</value>
</list>
</property>
</bean>
<jaxrs:server id="restServices" address="/rest">
<jaxrs:serviceBeans>
<ref bean="restUserService" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider" />
</jaxrs:providers>
</jaxrs:server>
Tom