moi
moi

Reputation: 2031

UnmarshalException when getting json array with Jersey

Our Application has a Class that wraps Jersey REST functionality. One Method is public <T extends Storable> List<T> retrieve(Class<T[]> pCls) throws StorageException, that is called like retrieve(Item[].class) to get the whole List of Items from the resource /items (see below).

The answer from the server is [{"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}], which is what I expect.

But the Application exits with Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException, with linked exception [com.sun.istack.internal.SAXParseException2; lineNumber: 1; columnNumber: 14; unexpected element (uri:"", local:"price"). Expected elements are <{}article>,<{}item>].

Code for retrieve (client):

ClientResponse cr = this.resource.path(resourcePath)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get(ClientResponse.class);

        T[] a = cr.getEntity(pCls);

Code for the resource (on the server):

@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();
    }
}

Code for Item:

@XmlRootElement
public class Item extends Article {
    private Category category;
    private double cost;
    private boolean available;
};

Upvotes: 1

Views: 1986

Answers (2)

moi
moi

Reputation: 2031

I solved the Problem by using Jackson like in this answer: https://stackoverflow.com/a/9725228/1116842

ClientConfig cfg = new DefaultClientConfig();
cfg.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(cfg);

Matt Ball says:

Jackson's MessageBodyReader implementation appears to be more well-behaved than the Jersey JSON one.

Upvotes: 2

pygospa
pygospa

Reputation: 53

I'm not quite sure, but it looks like you're expecting a JASON Object but are getting an XML one. Just found this on Stackoverflow, maybe it's applicable to your problem?

Getting JSON out put from restful java client

Upvotes: 0

Related Questions