菜鸡记录器 2015-08-17 09:50 采纳率: 0%
浏览 7388

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

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

  • 写回答

3条回答 默认 最新

  • threenewbee 2015-08-17 22:42
    关注
     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

    评论

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏