如何基于Key对JSON对象进行排序? [英] How can i sort my JSON object based on Key?

查看:1047
本文介绍了如何基于Key对JSON对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个JSON对象,我在其中添加一个键和一个数组值。 key和value的值来自TreeSet,它具有排序形式的数据。但是,当我在我的json对象中插入数据时,它是随机存储的,没有任何顺序。
这是我目前的json对象:

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. However, when I insert data in my json object, it is stored randomly without any order. This is my json object currently:

{
    "SPAIN":["SPAIN","this"],
    "TAIWAN":["TAIWAN","this"],
    "NORWAY":["NORWAY","this"],
    "LATIN_AMERICA":["LATIN_AMERICA","this"]
}

我的代码是:

 Iterator<String> it= MyTreeSet.iterator();

        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);
        }

我有什么方法可以将数据存储到while循环内部的json对象中吗?

Is there any way I can store the data into my json object inside the while loop itself?

推荐答案

适用于Google Gson API。尝试一下。

It works with Google Gson API. Try it out.

    try{

        TreeSet<String> MyTreeSet = new TreeSet<String>();
        MyTreeSet.add("SPAIN");
        MyTreeSet.add("TAIWNA");
        MyTreeSet.add("INDIA");
        MyTreeSet.add("JAPAN");

        System.out.println(MyTreeSet);
        Iterator<String> 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();
    }

这篇关于如何基于Key对JSON对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆