I have a class FoodItemImpl
which implements the interface FoodItem
.
I want to return list of FoodItem
using REST.
I couldn't
However, I can return list of FoodItemImpl
like this:
Wraper
enum wria {
instance;
private Map<Integer, FoodItemImpl> map = new HashMap<Integer, FoodItemImpl>();
public Map<Integer, FoodItemImpl> get() {
return this.map;
}
wria() {
List<FoodItem> LL = FoodItemImpl.getAllFoodItems();
for (int i = 0; i < LL.size(); i++) {
map.put(LL.get(i).getID(), (FoodItemImpl) LL.get(i));
}
}
}
REST Code
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<FoodItemImpl> getXML() {
List<FoodItemImpl> ll = new LinkedList<FoodItemImpl>();
ll.addAll(wria.instance.get().values());
return ll;
}
Your error states that you do not have a message body writer for the interface FoodItem
to the type application/xml. Now, assuming you are using JAXB as default mbw for XML:
JAXB cannot bind interfaces out of the box . You have to create an adapter:
public class AnyFoodItemAdapter extends XmlAdapter<Object,Object> {
Object unmarshal(Object v) { return v; }
Object marshal(Object v) { return v; }
}
And then annotate FoodItem:
@XmlJavaTypeAdapter(AnyFoodItemAdapter .class)
interface FoodItem {
...
}
See more details and other ways of doing this in: Project JAXB - Mapping Interfaces .
Try annotating your Interface Getter Methods (JAXB) to define the elements in your result XML. That should resolve your issue, I believe.
Instead of returning List, try having another XmlElement class (Interface if you want) which holds a list for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.