解析Rest客户端java的JSonObject响应

时间:2015-12-15 09:41:11

标签: json rest http-get jsonobject rest-client

我编写了RestClient来调用其余服务,然后解析响应。我用这个:

HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
 StringBuilder sb = new StringBuilder();
 String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
 }
  try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
    }
    jObj = new JSONObject(json);
  return jObj;

我得到这样的回应:

{\"r\":{\"@status\":\"ok\",\"@st\":\"ok\",\"@call_id\":\"8410e\",\"method\":\"notification\",\"notification\":" +
            "{\"@status\":\"true\",\"n\":{\"objects\":{\"@totalClassCount\":\"35\",\"@totalTestCount\":\"0\",\"@totalContentCount\":\"0\"," +
            "\"@totalAssignmentCount\":\"5\",\"@totalOverdueCount\":\"16\",\"@totalCourseCount\":\"97\",\"@lastClassTime\":\"01-01-1753 12:00:00\"," +
            "\"@lastTestTime\":\"01-01-1753 08:00:00\",\"@lastContentTime\":\"09-01-2015 02:52:30\",\"@lastAssgnTime\":\"01-01-1753 08:00:00\"," +
            "\"@lastOverdueTime\":\"01-01-1753 12:00:00\",\"@lastCourseTime\":\"09-01-2015 02:52:30\",\"@lastCommentTime\":\"14-12-2015 03:48:55\"," +
            "\"flag\":\"1\",\"object\":[{\"@type\":\"3\",\"content\":{\"@contentid\":\"137\",\"ntype\":\"1\",\"sime\":\"9 months ago\"," +
            "\"title\":{\"#cdata-section\":\"xlsx icon file\"},\"courseid\":\"95137\",\"sid\":\"1976\",\"subid\":\"0\",\"coursetype\":\"1\",\"contentsize\":" +
            "\"0\",\"csid\":\"2\",\"contenttypeid\":\"6\",\"contentviews\":\"0\",\"totalslides\":\"16\",\"iscreator\":\"0\"}}}]}}}}}

你能帮我解析一下吗?

谢谢, 编辑

1 个答案:

答案 0 :(得分:0)

转换为JSON的代码并不完全正确 - 尝试使用JSONObject。你可以做得更好,如下所示。

 if (httpEntity != null) {
           String resultString = EntityUtils.toString(httpEntity); 
           // parsing JSON and convert String to JSON Object
           JSONObject result = new JSONObject(resultString); 
     return result;