2015-05-13 145 views
1

我有一個REST服務和客戶端。我試圖調用此服務直接使用JSON並將其轉換爲我需要的對象。但它不起作用。我收到以下錯誤:未找到用於Java類com.a.b.c.D和Java類型類com.a.b.c.D和MIME媒體類型application/json的消息正文閱讀器。澤西REST服務不消費JSON

服務:

@Path("/getListPrice") 
public class ListPriceService { 

     @POST 
     @Consumes(MediaType.APPLICATION_JSON) 
     @Produces(MediaType.APPLICATION_JSON) 
     @Type(PricingObject.class) 
     public Response search(PricingObject pricingObject, @Context final HttpHeaders headers) { 
       ......... 
       return Response.ok().entity(pricingObject).build(); 
     } 
} 

客戶:

WebResource webResource = client.resource(url);    
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON) 
          .type(MediaType.APPLICATION_JSON_TYPE) 
          .post(ClientResponse.class, pricingObjectRequest); 

if (response.getStatus() != 200) { 
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); 
} 

誰能告訴我是什麼問題呢?

回答

0

A message body reader for Java class com.a.b.c.D, and Java type class com.a.b.c.D, and MIME media type application/json was not found

,如果你得到一個服務器端異常或客戶端異常你沒有說。如果是前者,你可能沒有JSON提供者,或者你有一個但沒有配置它。

這裏是提供

下面是web.xml配置

<init-param> 
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> 
    <param-value>true</param-value> 
</init-param> 

如果它是一個客戶端異常,我會假設你有以上的依賴性。然後配置客戶端

ClientConfig config = new DefaultClientConfig(); 
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); 
Client client = Client.create(config); 
+0

我已經將您提到的更改添加到了我的web.xml以及我的客戶端,但仍然遇到同樣的問題。 –

+0

這是服務器端問題嗎?這是你在哪裏得到例外?如果是的話,表明你的web.xml –

+0

我想通這個問題,沒有正確添加在init-PARAM和也不得不添加此 \t \t \t​​com.sun.jersey.config.property.resourceConfigClass \t \t \t com.sun.jersey.api.core。PackagesResourceConfig \t \t

-1

您可以修改您的資源類,如下

/**<code> 
    * { 
    * "id"=1, 
    * "name="priceitem1" 
    * } 
    * </code> 

    **/ 
    @POST 
    @Consumes(MediaType.APPLICATION_JSON) 
    @Produces(MediaType.APPLICATION_JSON) 
    public Response search(PricingObject pricingObject) { 
     JSONArray jsarray=new JSONArray(); 
     jsarray.put(pricingObject); 
     return Response.ok().entity(jsarray.toString()).build(); 
    } 

WHCI是在標籤之間的數據是JSON數據,將來自客戶端。

你可以按照以下

public class PricingObject { 
@XmlElement(name="id") 
private int id; 
@XmlElement(name="name") 
private String name; 

public int getId() { 
    return id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

}

的@XmlElement配置你的bean類將綁定JSON鍵與你的bean類變量。

0

您需要配置Jersey以使用句柄Json - > Object mapping。使用Jersey 1,您需要將json提供程序添加到您的依賴項中,例如

<dependency> 
    <groupId>com.sun.jersey</groupId> 
    <artifactId>jersey-json</artifactId> 
    <version>1.17.1</version> 
</dependency> 
+0

好的,我在哪裏做到這一點?我正在使用Jersey 1.17.1 maven dependency。 –

+0

我已經更新了答案,並給出了您正在使用的版本的maven示例 – tddmonkey

+0

我已經有了這個依賴關係,我仍然遇到同樣的問題,甚至嘗試了下面的答案,但沒有運氣。 –