如何将String转换为JSON OBJECT

时间:2011-07-01 07:41:59

标签: android

我得到一个例外:

  

java.lang.Boolean无法转换为JSONObject

如何删除此例外?

HttpGet request = new
    HttpGet("http://xxxxxxxxxxxx/REST/MobileService.svcisApproved?DeviceID=123");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
String changeTIDRec = EntityUtils.toString(responseEntity);
JSONObject jsonResponse = new JSONObject(changeTIDRec);

2 个答案:

答案 0 :(得分:1)

您需要这种方法:

 private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(
    new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
} catch (IOException e) {
    // Log.e(TAG, e.getMessage(), e);
    throw new RuntimeException(e.getMessage(), e);
} finally {
    try {
    is.close();
    } catch (IOException e) {
    // Log.e(TAG, e.getMessage(), e);
    throw new RuntimeException(e.getMessage(), e);
    }
}
return sb.toString();
}

它的使用方式如下:

InputStream instream = entity.getContent();
        response = convertStreamToString(instream);

答案 1 :(得分:0)

为什么不使用Gson

String test = "test string";
Gson gson = new Gson();
gson.toJson(test);