我们的应用程序有一个包含Jersey REST功能的类。一种方法是public <T extends Storable> List<T> retrieve(Class<T[]> pCls) throws StorageException
,称为retrieve(Item[].class)
,用于从资源/items
获取整个项目列表(见下文)。
来自服务器的答案是[{"price":1.0,"specialPrice":0.0,"name":"Beverage","special":false,"category":"BEVERAGE","cost":0.0,"available":false,"id":0},{"price":2.0,"specialPrice":0.0,"name":"Meal","special":false,"category":"DISH","cost":0.0,"available":false,"id":0}]
,这正是我所期望的。
但是应用程序退出Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException
,链接异常[com.sun.istack.internal.SAXParseException2; lineNumber: 1; columnNumber: 14; unexpected element (uri:"", local:"price"). Expected elements are <{}article>,<{}item>]
。
ClientResponse cr = this.resource.path(resourcePath)
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
T[] a = cr.getEntity(pCls);
@Path("/items")
public class ItemListResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getItemList() {
LinkedList<Item> l = new LinkedList<Item>();
l.add(new Item(1.0, "Beverage", Category.BEVERAGE));
l.add(new Item(2.0, "Meal", Category.DISH));
return Response.ok(l).build();
}
}
@XmlRootElement
public class Item extends Article {
private Category category;
private double cost;
private boolean available;
};
答案 0 :(得分:2)
我在答案中使用杰克逊解决了问题:https://stackoverflow.com/a/9725228/1116842
ClientConfig cfg = new DefaultClientConfig();
cfg.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(cfg);
Matt Ball说:
Jackson的MessageBodyReader实现似乎比Jersey JSON实现更好。
答案 1 :(得分:0)
我不太确定,但看起来你期待一个JASON对象,但正在获得一个XML。刚刚在Stackoverflow上找到了这个,也许它适用于您的问题?