2012-04-02 62 views
1

我收到的错误:的Java使用来自REST服务的JSON列表GET

SEVERE: A message body reader for Java class java.util.List, 
and Java type java.util.List<com.testapp.Category>, 
and MIME media type text/html; charset=utf-8 was not found 

试图消耗使用与新泽西GET方法REST服务的JSON响应。从服务器的响应看起来是这样的,当我用卷曲:

[{"category":{"id":"4d9c5dfc8ddfd90828000002","description":"Cows"}}, 
{"category":{"id":"4d9c5dfc8ddfd90828000023","description":"Dogs"}}, 
... 
{"category":{"id":"4d9c5dfc8ddfd90828000024","description":"Mules"}}] 

与消费服务:

public List<Category> getAnimalCategories(Cookie cookie) { 
    Client client = Client.create(new DefaultClientConfig()); 
    ClientResponse response = client 
     .resource(Constants.BASE_URL) 
     .path(Constants.CATEGORIES_ANIMALS) 
     .accept(MediaType.APPLICATION_JSON) 
     .type(MediaType.APPLICATION_JSON) 
     .cookie(cookie) 
     .get(ClientResponse.class); 

    return response.getEntity(new GenericType<List<Category>>(){}); 
} 

其中Category.java是:

public class Category { 

public String id; 
public String description; 

public Category() { 
} 

public Category(String id, String description) { 
    super(); 
    this.id = id; 
    this.description = description; 
} 

该服务使用基于Cookie身份验证 - 该部分工作,我有其他服务调用与cookie一起工作。

+0

可能重复使用Jersey客户端的JSON数组对象](http://stackoverflow.com/questions/9627170/cannot-unmarshal-a-json-array-of-objects-using-jersey-client) – 2012-04-02 20:38:09

+0

通过添加Jackson 1.9修复。 6 jar并添加到ClientConfig中: clientConfig.getClasses()。add(Jackso nJsonProvider.class); – 2012-04-02 21:34:40

回答

5

使用的杰克逊1.9.6 LIB来解决此问题 - 请参阅下面的第2行:

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

return client 
    .resource(Constants.BASE_URL) 
    .path(Constants.CATEGORIES_ANIMALS) 
    .type(MediaType.APPLICATION_JSON) 
    .accept(MediaType.APPLICATION_JSON) 
    .cookie(cookie) 
    .get(new GenericType<List<AnimalCategoryResponse>>(){}); 

也需要使用新的响应类:

public class AnimalCategoryResponse { 
    public Category[] category; 
    public AnimalCategoryReponse() { } 
} 
的[无法解组
+0

谢谢我有这个问题很长一段时间,我在球衣文档中看到它会扫描提供程序的类路径,JacksonProvider会自动发现,但这看起来不正确。在加入JacksonJsonProvider之后,我的代码就可以工作了。 – 2013-09-19 15:09:50