How can i sort my JSON object based on Key?

后端 未结 3 1440
南旧
南旧 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:42

    It works with Google Gson API. Try it out.

        try{
    
            TreeSet MyTreeSet = new TreeSet();
            MyTreeSet.add("SPAIN");
            MyTreeSet.add("TAIWNA");
            MyTreeSet.add("INDIA");
            MyTreeSet.add("JAPAN");
    
            System.out.println(MyTreeSet);
            Iterator it= MyTreeSet.iterator();
            JsonObject gsonObj = new JsonObject();
            JSONObject jsonObj = new JSONObject();
            while (it.hasNext()) {
                String country = it.next();
                System.out.println("----country"+country);
                JSONArray jsonArray = new JSONArray();
                jsonArray.put(country);
                jsonArray.put("this");
    
                jsonObj.put(country, jsonArray);
    
                JsonArray gsonArray = new JsonArray();
    
                gsonArray.add(new JsonPrimitive("country"));
                gsonArray.add(new JsonPrimitive("this"));
                gsonObj.add(country, gsonArray);
            }
            System.out.println(gsonObj.toString());
            System.out.println(jsonObj.toString());
    
    
    
    
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

提交回复
热议问题