2014-02-20 38 views
0

我正試圖從android調用澤西寧靜的web服務。我的Android代碼是未找到適用於Java類型,類org.json.JSONObject ....和MIME媒體類型,application/json的消息正文閱讀器

客戶端代碼:

HttpClient httpClient = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://X.X.X.X:8080/RestfulService/rest/post"); 
post.setHeader("content-type", "application/json"); 

JSONObject dato = new JSONObject(); 
dato.put("email", email); 
dato.put("password", password); 

StringEntity entity = new StringEntity(dato.toString()); 
post.setEntity(entity); 
HttpResponse resp = httpClient.execute(post); 
String rs = EntityUtils.toString(resp.getEntity()); 
return rs 

Webservice的代碼

@POST 
@Produces({ MediaType.APPLICATION_JSON }) 
@Consumes({ MediaType.APPLICATION_JSON }) 
public String AuthMySQL(JSONObject json) { 

String password = (String) json.get("password"); 
String email = (String) json.get("email"); 

*I am using the string values to get the result from the database* 

} 

我的錯誤是一樣的東西com.sun.jersey.api.client.ClientHandlerException:消息正文閱讀器爲Java類型,類org.json.JSONObject ....和MIME媒體類型,application/json未找到。

你的幫助是非常讚賞

+0

可能重複:http://stackoverflow.com/questions/12048804/a-message-body-writer-for- java-type-class-net-sf -json-jsonobject-and-mime-medi –

+0

你能列出附加到你的服務項目的庫文件嗎? – Joshi

+0

@Joshi我已經包括所有球衣1.18 jar文件 – Mahi

回答

0

,當你沒有得到正確的庫包含的JSON正確映射到一個POJO,或者沒有爲輸入適當的POJO出現這種情況。

看看添加的jersey-json maven dependency到項目

0

如果你不想添加庫,只是想在解析的JSON(即沒有映射到一個POJO),那麼你可以實現基本MessageBodyReader,如:

public class JSONObjectMessageBodyReader implements MessageBodyReader<JSONObject> { 
    @Override 
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { 
     return type == JSONObject.class && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); 
    } 

    @Override 
    public JSONObject readFrom(Class<JSONObject> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { 
     try { 
      // Using Apache Commons IO: 
      String body = IOUtils.toString(entityStream, "UTF-8"); 
      return new JSONObject(body); 
     } catch(JSONException e) { 
      throw new BadRequestException("Invalid JSON", e); 
     } 
    } 
} 

然後在您的Web服務代碼:

@POST 
public Response doSomething(JSONObject body) { 
    ... 
} 
相關問題