如何基于Key对JSON对象进行排序?

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

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

我的代码是:

  Iterator 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对象中吗?

它适用于Google Gson API。 试试看。

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

即使这篇文章很老,我认为没有GSON也值得发布一个替代方案:

首先将您的密钥存储在ArrayList中,然后对其进行排序并遍历密钥的ArrayList:

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

以下是http://www.json.org/java/index.html上的文档。

“JSONObject是一个无序的名称/值对集合。”

“JSONArray是一个有序的值序列。”

为了获得一个已排序的Json对象,你可以使用Gson,它已经被@ user748316提供了一个很好的答案。