JSONException:类型java.lang.String的值无法转换为JSONArray

时间:2014-12-19 06:31:48

标签: java android json

我正在使用的代码:

try {
       resultObject = new JSONObject(URLDecoder.decode(result, "UTF-8"));// no problem here
       resultJsonArray = resultObject.getJSONArray("data"); // error comes when run this line.

    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

这是完整的错误信息:

org.json.JSONException: Value [{"first_name":"aig","phone_no":"3659428","passcode":"aig","last_name":"aig","user_id":"03343785-2714-43a5-a566-f4d9877ccafa","email_id":"aig.science@gmail.com"},{"first_name":"aig","phone_no":"635448448","passcode":"aig","last_name":"aig","user_id":"5dc26dcc-3f81-434a-b293-48438f2f920a","email_id":"aig.science@gmail.com"}] at data of type java.lang.String cannot be converted to JSONArray

格式化后(http://jsonformatter.curiousconcept.com/),JSON字符串将如下所示:

{  
   "response":"Success",
   "tablename":"USER_INFO",
   "transaction_type":"MODIFICATION_PULL_RESPONSE",
   "data":"[{\"first_name\":\"aig\",\"phone_no\":\"3659428\",\"passcode\":\"aig\",\"last_name\":\"aig\",\"user_id\":\"03343785-2714-43a5-a566-f4d9877ccafa\",\"email_id\":\"aig.science@gmail.com\"},{\"first_name\":\"aig\",\"phone_no\":\"635448448\",\"passcode\":\"aig\",\"last_name\":\"aig\",\"user_id\":\"5dc26dcc-3f81-434a-b293-48438f2f920a\",\"email_id\":\"aig.science@gmail.com\"}]"
}

3 个答案:

答案 0 :(得分:0)

你做错了。尝试下面的代码:

try {

   resultJsonArray = resultObject.getJSONArray(result);

} catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

答案 1 :(得分:0)

请避免“”(双引号字符)在解析时直接导致JSON异常,始终使用\在这些字符之前,

字符串是零个或多个Unicode字符的序列,用双引号括起来,使用反斜杠转义符。字符表示为单个字符串。字符串非常类似于C或Java字符串。 它可以帮到你。

答案 2 :(得分:0)

After testing for a while, I solved it in a wired way:

**Before:**

       try {
          resultObject = new JSONObject(URLDecoder.decode(result, "UTF-8"));// no problem here
          resultJsonArray = resultObject.getJSONArray("data"); // error comes when run this line.

       } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
       }


**After**

      try {
          resultObject = new JSONObject(URLDecoder.decode(result, "UTF-8"));// no problem here
          resultJsonArray = new JSONArray(resultObject.get("data").toString()); // Works!!!

       } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
       }

真的很有线。我不知道为什么会这样。