I'm connecting to a remote server which I do not have control over. The JSON that is send back includes a root element.
{"company":{"name":"Personal"}}
When trying to unmarshall the string into a company object I get the following error: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "company"
Below is my configuration in my test class. I'm using JUnit 4.12, Jersey-client 1.19 and Jersey-json 1.19
@XmlRootElement
public class Company{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Company{" + "name=" + name + '}';
}
}
The test client:
public class CompanyResourceTest {
@Test
public void createClient() {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8686/voucher-test/rest/company");
String companyName = "Personal";
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, companyName );
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus() + ", " + response.getStatusInfo());
}
Company json = response.getEntity(Company.class);
}
}
What can I do to unmarshall the JSON string?
Create a Wrapper class that will have the Company object as a property. e.g.,
@XmlRootElement
public class CompanyResponse{
private String company;
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company= company;
}
}
Then, use this class to get the response from the server. i.e., change the following
Company json = response.getEntity(Company.class);
to
Company json = response.getEntity(CompanyResponse.class).getCompany();
UPDATE
As suggested by @JuanDM, including the name
attribute in the @XmlRootElement
also works:
@XmlRootElement(name="company")