使用Jersey获取json数组时出现UnmarshalException

时间:2012-09-14 11:21:46

标签: java json jersey

我们的应用程序有一个包含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;
};

2 个答案:

答案 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上找到了这个,也许它适用于您的问题?

Getting JSON out put from restful java client