Android:java.lang.String无法转换为JSONArray

时间:2016-10-03 06:15:13

标签: java android json loopj

我在尝试将字符串解析为jsonArray时遇到json异常。我正在使用loopj方法进行json解析。这是错误:

java.lang.String cannot be converted to JSONArray

这是我试图解析的json:

[{\"displayName\":\"Thiruvananthapuram\",\"desc\":\"Partly cloudy\",\"cloudCover\":\"5\",\"dateTime\":\"Sunday October 02\",\"humidity\":\"85\",\"visibility\":\"10\",\"tempCelcius\":\"29\",\"iconClass\":\"PartlyCloudy-s\"}]

我的代码是

    AsyncHttpClient client = new AsyncHttpClient();
   client.get("url", new AsyncHttpResponseHandler() {
    @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

        try {
        String jsonStr = new String(responseBody, "UTF-8");
        Log.e("Tag ", "on Result " + jsonStr);
        JSONArray jsonarray = new JSONArray(jsonStr);
                Log.e("Tag ", "jsonArr length " + jsonarray.length());
        }
        catch (UnsupportedEncodingException e)
        {
          e.printStackTrace();
        }
        catch (Exception e)
        {
          e.printStackTrace();
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        }
    })

2 个答案:

答案 0 :(得分:1)

首先,您必须使用jsonString使用下面的行

来获取jsonObject
JSONObject jsnobject = new JSONObject(jsonStr);

然后你可以遍历jsonObject来获取jsonArray对象。

JSONArray jsonArray = jsnobject.getJSONArray("your json array key");

答案 1 :(得分:0)

你必须将“\”替换为“”然后转换为JsonArray: -

例如: -

 String jsonStr = new String(responseBody, "UTF-8");

jsonStr = jsonStr.replace("\","");

// now convert it into JsonArray
  JSONArray jsonarray = new JSONArray(jsonStr);

希望这能帮到你......