sunny
sunny

Reputation: 1945

how to return List<MyObject> with REST call?

I make a REST call and I want to get back json, that contains list of MyClass objects. Actually I get this exception:

javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.internal.SAXParseException2; lineNumber: 0; columnNumber: 5; unexpected element (uri:"", local:"id"). Expected elements are <{}snowCannonDataEntity>]

THE CODE:

public List<'MyClass> getLIst()

{
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(MyObjectMapper.class);
Client client = Client.create(config);
WebResource resource = client.resource(HOST_PATH).path(PATH).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE);
return resource.get(new GenericType<List<MyClass>>() {
    });
}


@XmlRootElement
public class MyClass
{ ... }

Upvotes: 0

Views: 1387

Answers (2)

Geert
Geert

Reputation: 3777

According to the suggestion of Paul Sandoz your code is indeed the way to go.

However, if this does not work, use the Jackson JSON provider instead of the default JAXB one. This did the trick for me:

import org.codehaus.jackson.jaxrs;

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

Upvotes: 1

Martin Matula
Martin Matula

Reputation: 7989

The json returned from the server could not be parsed for some reason. You have to show us MyClass source as well as the json that comes from the server. You can print out the JSON coming from the server by requesting String instead of List:

ClientConfig config = new DefaultClientConfig();
config.getClasses().add(MyObjectMapper.class);
Client client = Client.create(config);
WebResource resource = client.resource(HOST_PATH).path(PATH).accept(MediaType.APPLICATION_JSON_TYPE);
System.out.println(resource.get(String.class));

Upvotes: 0

Related Questions