我有一个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
}
}
]
我尝试将字符串转换为JSONObject,但错误表明它是JSONArray。
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)
答案 0 :(得分:1)
您的错误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
答案 1 :(得分:0)
例如,如果您从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*/
}
希望有所帮助
答案 2 :(得分:0)
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();
}