How can i sort my JSON object based on Key?

后端 未结 3 1438
南旧
南旧 2021-01-13 18:55

I am creating a JSON object in which i am adding a key and a value which is an array. The value for both key and value comes from a TreeSet which has data in sorted form. Ho

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 19:32

    Even if this post is quite old, I thought it is worth posting an alternative without GSON:

    First store your keys in an ArrayList, then sort it and loop through the ArrayList of keys:

    Iterator it= MyTreeSet.iterator();
    ArrayListkeys = new ArrayList();
    
    while (it.hasNext()) {
        keys.add(it.next());
    }
    Collections.sort(keys);
    for (int i = 0; i < keys.size(); i++) {
        String country = keys.get(i);
        System.out.println("----country"+country);
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(country);
        jsonArray.put("this");
    
        jsonObj.put(country, jsonArray);
    }
    

提交回复
热议问题