2013-10-21 132 views
1

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

{ 
    "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对象?

+3

标准JSON对象是一组*无序*键/值对。它不能被“分类”。 –

+0

顺便说一句,你的插图与你的代码不符。您的插图仅包含对象,不包含数组。 –

+0

1.将它作为数组移动到Object 2.将您的数组排除 –

回答

0

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

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

非常感谢好友。它工作得很好,得到了我的预期... :) – AppleBud

0

以下是医生在http://www.json.org/java/index.html之间说的内容。

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

“A JSONArray是值的有序序列。”

为了得到一个排序的JSON对象,你可以使用GSON其已经提供由@ user748316一个很好的答案。

3

即使这个职位是很老,我认为这是值得张贴替代无GSON:在一个ArrayList

第一店你的钥匙,然后通过按键的ArrayList排序并循环:

Iterator<String> it= MyTreeSet.iterator(); 
ArrayList<String>keys = 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); 
} 
+0

迄今为止我找到的最整洁的答案。谢谢! –

相关问题