在java.lang.String类型的0处无法转换为JSONArray

时间:2015-06-04 15:17:09

标签: java android json

我在0的java.lang.String类型中遇到此异常无法转换为JSONArray,不知道为什么?我之前在不同的工作中使用过这个例外

List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
  success = json.getInt(TAG_SUCCESS);
  Routearrray = new ArrayList<String>();
} catch (JSONException e) {
  e.printStackTrace();
}
try {
  if (success == 1) {
    JSONArray jsonarray;
    json = new JSONObject(JSONParser.Result);
    JSONArray jArray = json.getJSONArray("data");
    for (int i = 0; i <= jArray.length(); i++) {
      jsonarray = jArray.getJSONArray(i);
      Stopnames = jsonarray.getString(0);
      Counter++;
      if (Counter <=jArray.length()) {
        //Routearrray.add(Stopnames);
        Log.d("Stop name:", Stopnames);
        //Log.d("Route name:", Routearrray.toString());
      } else {
        break;
      }
    }

JSON网址

{
  "data":[
         "Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
         "Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
         "Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
         "Zero Point","Children Hospital","F-8\/4","Ali Hospital"
  ],
  "success":1,
  "status":200,
  "status_message":"Login Successfull"
}

错误:在行

 jsonarray = jArray.getJSONArray(i);

5 个答案:

答案 0 :(得分:1)

从你的JSON,jArray是一个String数组,而不是JSONArray数组。
替换:

jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);

使用:

Stopnames = jArray.getString(i);

答案 1 :(得分:0)

for循环应该是

for (int i = 0; i < jArray.length(); i++) {

答案 2 :(得分:0)

您尝试将字符串值解析为JSONArray。 jArray是一个字符串数组,而不是JSONArrays,所以你需要做的就是从中提取字符串值。

JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
    Log.d("Stopnames: " , jArray.getString(i));
    ....
}

答案 3 :(得分:0)

那是因为你&#34;数据&#34;是json数组类型。里面是什么&#34;数据&#34;不是jsonarray,它们只是jsonstrings。

更改以下行

jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);

stopnames += jArray.getString(i);

答案 4 :(得分:0)

你正试图从jsonarray获取jsonarray,而json数组包含json对象。试试这个

JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))