如何解析 android 中的 jsonArray?

how to parse jsonArray in android?

我得到了 JSON,我正在尝试根据值解析和排序分数。我什至无法解析它。以下是我的 JSON 回复。

[
      {"scores":
        { "a":1.460211E-17,
          "b":3.808661E-20,
          "c":3.07329371E-14,
          "d":1.02141569E-17,
          "e":1,
          "f":6.26432543E-12,
          "g":3.75437664E-14,
          "h":1.877707E-21
        },
      "rectangle":
       { "left":142,
         "width":882,
         "top":0,
         "height":848
       }
     }
    ]

我试图将字符串转换为 JSON 对象,但错误提示它是 JSON 数组。

JSONObject reader = new JSONObject(json);
JSONArray jsonArray = reader.optJSONArray("scores");

出现类似

的错误
org.json.JSONException: Value of type org.json.JSONArray cannot be converted to JSONObject

所以我认为该值已经是一个 JSON 数组。我尝试了以下代码......

JSONArray jsonArray = reader.optJSONArray("scores");

JSONArray cast = jsonResponse.getJSONArray("scores");

...但会引发以下错误:

cannot resolve method optJSONArray()java.lang.String)
cannot resolve method getJSONArray()java.lang.String)

您的错误 org.json.JSONException: Value of type org.json.JSONArray cannot be converted to JSONObject 清楚地表明您正在尝试将 JSONArray 解析为 JSONObject

这样做

JSONArray reader = new JSONArray(json);
JSONObject jsonArray = reader.getJSONObject(0).optJSONObject("scores"); // replace 0 with your own index

试试这个,例如,如果您从 HTTP 请求中获得 Json:

HttpPost httppost = new HttpPost( "http://www.somepage.php" );

HttpParams mHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(mHttpParams, myConnectionTimeOut );
HttpConnectionParams.setSoTimeout(mHttpParams, myTimeOut);

HttpClient httpclient = new DefaultHttpClient( mHttpParams );
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader( entity.getContent() ));
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = rd.readLine()) != null) {
    sb.append(line  );
}

JSONArray jsonArray = json.getJSONArray("scores");

for( int i = 0; i < jsonArray .length(); i++ ) { 
    /* Do what you want here*/                                                          
}

希望对您有所帮助

try {
        JSONArray array= new JSONArray("your string");

        JSONObject object= array.getJSONObject(0);
        JSONObject
         scores=object.getJSONObject("scores");
        String [] subjects={"a","b","c","d","e","f","g","h"};
        for(int i=0;i<subjects.length;i++){

            Log.e("TAG",scores.getString(subjects[i]));

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