开发者社区 问答 正文

在java中JSON如何进行字典排序

由于工作项目的关系,不能导入外部jar包,现有的JSONObject是org.json.JSONObject下的

展开
收起
杨冬芳 2016-07-05 17:21:00 5520 分享 版权
1 条回答
写回答
取消 提交回答
  • IT从业
    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

     0

    2019-07-17 19:51:42
    赞同 展开评论