由于工作项目的关系,不能导入外部jar包,现有的JSONObject是org.json.JSONObject下的
public static void main(String[] args) {
String str = "{'TI':[{'value':'aa1','count':10},{'value':'aa2','count':15},{'value':'aa3','count':20}]," +
"'AB':[{'value':'ab','count':110},{'value':'ab2','count':115},{'value':'ab3','count':210}]}";
JSONArray newArray = new JSONArray();
JSONObject newJson = new JSONObject();
try {
JSONObject obj = new JSONObject(str);
Iterator it = obj.keys();
while (it.hasNext()) {
String key = (String) it.next();
String value = obj.getString(key);
JSONArray array = obj.getJSONArray(key);
for(int i=0;i<array.length();i++){
JSONObject jsonobject = array.getJSONObject(i);
jsonobject.put("name", key);
jsonobject.put("exp", key+"="+jsonobject.getString("value"));
newArray.put(jsonobject);
}
}
newJson.put("groups",newArray);
System.out.println(newJson);
} catch (JSONException e) {
e.printStackTrace();
}
}
解析json
然后排序
JSONArray mJSONArray;
protected void sortJsonArrayByDate(String dateName){
List<JSONObject> list = new ArrayList<JSONObject> ();
JSONObject jsonObj = null;
for (int i = 0; i < mJSONArray.length(); i++) {
jsonObj = mJSONArray.optJSONObject(i);
list.add(jsonObj);
}
//排序操作
JsonComparator pComparator = new JsonComparator(dateName);
Collections.sort(list, pComparator);
//把数据放回去
mJSONArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
jsonObj = list.get(i);
mJSONArray.put(jsonObj);
}
}
public class JsonComparator implements Comparator<JSONObject>{
String dateName = "";
JsonComparator(String dateName){
this.dateName = dateName;
}
@Override
public int compare(JSONObject json1, JSONObject json2){
String date1 = json1.optString(dateName);
String date2 = json2.optString(dateName);
if(date1.compareTo(date2) < 0){
return 1;
}else if(date1.compareTo(date2) >0){
return -1;
}
return 0;
}
}
http://www.tuicool.com/articles/ne2uyij
在数据装载之前就先排序好,然后在json啊
这只能单层排序吧,如果json里面是个list呢