I recently came across a very nice requirement where a REST service was required to produce a response both in JSON and XML format.
However, there is a bug with JDeveloper and the automatic generation of EJB/TopLink Entity annotations. This bug is reproduced when you choose to generate a REST service on that automatically generated EJB entity and you choose to produces both a JSON and an XML response.
What's even trickier is that this bug is only revealed at runtime when you choose to parse an XML response. It will throw an Internal Server Error (500) and if you inspect the log files you will see the following trace:
MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList, genericType=java.util.List
So let's see in details how to reproduce this bug and how to fix it.
I will create a new application using the "Custom Application" template and will provide an application (bug-with-rest-service-app) and a project name (bug-with-rest-service).
So right-click your project, choose "New" and from the context-menu select "Java Service Facade (JPA/TopLink). Specify a package for storing your facade and click "Next".
If you run the test client you should get a list of countries printed in the log window.
There are several ways to do that. We can very just right click our facade and create a REST service. However, this would result in a really bad design pattern. I highly recommend that you create a "wrapper" class on top of the facade and then expose that "wrapper" class as a REST service.
So right click your project, select "New" and select "Java Class". Give your Java class a name, specify a package and click "OK".
You should have your "getAllCountries" method listed under the "Configure HTTP Methods" section.
If you inspect your Java class you should notice that it has been "decorated" with various annotations to instruct the runtime JVM engine to treat this class as a REST service.
The answer relies on the @Produces annotation in our Java class. The media type definition order is crucial. As we can see in our class, JSON is configured first and XML is configured as the alternative media type.
MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList, genericType=java.util.List<com.antonis.antoniou.rest.bug.entities.Countries
To fix this exception we need to decorate our "Countries" class with two additional annotations to instruct the engine to perform the proper Java to XML mapping. Therefore add the @XmlRootElement annotation just above the @Entity annotation to map the entire class to be the root XML element and just before each get method (getCountryId, getCountryName and getRegionId) add the @XmlElement annotation to map the countryId, countryName and regionId properties to XML elements.
REST Service Producing JSON & XML Response Bug and Fix in JDeveloper 12.2.1