2013-10-21 131 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

迄今爲止我找到的最整潔的答案。謝謝! –

相關問題