我有一个类似下面的JSONArray,我需要按id_cat标签按升序排序。
{
"item_cat": [
{
"82": {
"name": [
{
"id_cat":"2",
"name_cat": "red"
}
],
"data":[...]
},
"83":{
"name":[
{
"id_cat":"3",
"name_cat":"black"
}
],
"data":[...]
},
"84": {
"name": [
{
"id_cat":"4",
"name_cat": "green"
}
],
"data":[...]
},
}
]
}
我已经成功解析了JSON,但顺序并不恰当。 我尝试使用collections.sort对其进行排序,如下面的json array discussed
EDIT, 这是我的代码:
...
JSONArray ikatarray = ikat.getJSONArray("item_cat");
List<JSONObject> jsons1 = new ArrayList<JSONObject>();
for (int cb = 0; cb < ikatarray.length(); cb++) {
JSONObject cd = ikatarray.getJSONObject(cb);
Iterator ikatkeys = cd.keys();
while (ikatkeys.hasNext()) {
String item = (String) ikatkeys.next();
JSONObject data = cd.getJSONObject(item);
JsonArray name = data.getJSONArray("name");
ArrayList<JSONObject> jsons = new ArrayList<JSONObject>();
for (int c = 0; c < name.length(); c++) {
jsons.add(name.getJSONObject(c));
Collections.sort(jsons, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject lhs,JSONObject rhs) {
String lid = null;
try {
lid = lhs.getString("id_cat");
} catch (JSONException e) {
e.printStackTrace();
}
String rid = null;
try {
rid = rhs.getString("id_cat");
} catch (JSONException e) {
e.printStackTrace();
}
return lid.compareTo(rid);
}
});
JSONArray a = new JSONArray(jsons);
for (int b = 0; b < a.length(); b++) {
JSONObject k = a.getJSONObject(b);
String namecat = k.getString("name_cat");
Log.d("print: ", namecat.toString());
TextView labelName = new TextView(
Tabel2.this);
labelName.setId(200 + count);
labelName.setText(namecat);
labelName.setGravity(Gravity.LEFT);
labelName.setTextColor(Color.BLACK);
tr.addView(labelName);
}
}
}
}
}
logcat的输出:
Log.d("print: ", jsons.toString());
-----------------log cat ---------------
print: [{"id_cat":"2","name_cat":"red"}]
print: [{"id_cat":"4","name_cat":"green"}]
print: [{"id_cat":"3","name_cat":"black"}]
怎么可能这样做?