user2387331
user2387331

Reputation: 99

REST A message body writer for Java class java.util.LinkedList

This is my web service code

@Path("/totti")
public class KK {
    @GET
    @Produces(MediaType.TEXT_XML)
    public List<FoodItem> getRestarantsFordBrowser() {
        return FoodItemImpl.getAllFoodItems();
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public List<FoodItem> getXML() {
        return FoodItemImpl.getAllFoodItems();
    }
}

The foodItem is an interface.

The foodItemImpl is a class which implements the FoodItem interface. Also this class begins with @XmlRootElement(name = "FoodItem")

the getAllFoodItems() is a static method, its code is

    @XmlElement(name="Item")
        public static List<FoodItem> getAllFoodItems() {
return new LinkedList<FoodItem>();
    }

when I run the web service I got this exception

: A message body writer for Java class java.util.LinkedList, and Java type java.util.List<com.myP.eattel.food.FoodItem>, and MIME media type application/xml was not found
    ... 24 more

I have been trying to solving this exception for 5 hours, I googled a lot all the threads and solutions didn't help me

Edit

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>myP.webservices</display-name>
    <servlet>
        <servlet-name>Eattel REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.myP.eattel</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Eattel REST Service</servlet-name>
        <url-pattern>/eattel/*</url-pattern>
    </servlet-mapping>
</web-app>

Upvotes: 0

Views: 1778

Answers (2)

Matthew Gilliard
Matthew Gilliard

Reputation: 9498

I think it makes sense to wrap your List in a simple object:

  • Solves your problem simply and easily.
  • Allows you to extend the response format (eg add metadata to your list like paging, sorting) without a breaking change.
  • Avoids security problems if you also marshal to JSON (ref).

Upvotes: 0

harsh
harsh

Reputation: 7692

Can you add following in <servlet> tag:

         <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>

Upvotes: 1

Related Questions