【发布时间】:2016-03-25 07:13:43
【问题描述】:
我正在尝试对来自 JSONArray 的分数进行排序并仅输出前 10 名。这是我的代码。
try {
JSONArray jArray = new JSONArray(result);
List<String> jsonValues = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++)
jsonValues.add(jArray.getString(i));
Collections.sort(jsonValues);
JSONArray sortedJsonArray = new JSONArray(jsonValues);
for(int i=0;i<10;i++){
JSONObject jObject;
try {
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse((String) sortedJsonArray.get(i));
Score score =new Score();
score.setId(obj.getInt("Id"));
score.setPlayerId(obj.getInt("PlayerId"));
score.setHiScore(obj.getInt("HiScore"));
tempList.add(score);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我想将 sortedJsonArray 解析为 JSONObject,这就是我使用 org.json.simple.JSONObject 的原因,但它说它不能转换为 JSONObject。我尝试对 obj 使用 org.json.simple.JSONObject 数据类型,但出现此错误
The method getInt(String) is undefined for the type JSONObject
我正在从网络服务器检索数据
List<Score> tempList = new ArrayList<Score>();
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(EndPoint+"/Scores");
String result="";
HttpResponse response;
try {
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
if(entity!=null){
InputStream instream = entity.getContent();
StreamConverter sc= new StreamConverter();
result= StreamConverter.convertStreamToString(instream);
instream.close();
}
编辑
我意识到我可以使用 (String) 将 JSONArray 解析为字符串,而不使用 JSONParse。 -____-
jObject = new JSONObject((String) sortedJsonArray.get(i));
【问题讨论】:
-
请在此处发布 json
-
试试这个 JSONObject obj = (JSONObject) parser.parse(sortedJsonArray.get(i));
-
Khizar Hayat 我试过了,它说 sortedJsonArray 是一个对象,而 JSONParser 接受字符串。
-
你能发布你的进口声明吗?看来您正在使用不同的库developer.android.com/reference/org/json/JSONObject.html。是 JSONOBject。但是你有 org.json.simple.JSONObect。检查你的 json 和 android 上的 import 语句
标签: java android arrays json jsonobject