2011-02-08 130 views
0

我正在嘗試通過inner2然後inner3編寫內部跟隨。然而,現在它是inner2,inner3然後是inner1。如何根據我想要的順序編寫JSON對象?對JSON序列進行排序

public void toJSON(String description, String Name) 
{ 
    JSONObject inner = new JSONObject(); 
    JSONObject inner2= new JSONObject(); 
    JSONObject inner3= new JSONObject(); 

    try { 
    outer.put("DATA 1", inner); 
    inner.put("description", description); 
    inner.put("filename", imageName); 

    outer.put("DATA 2", inner2);  
    inner2.put("model", "modelname"); 

    outer.put("Datetime", inner3); 
    inner3.put("Datetime", "DateTime"); 

    } catch (JSONException ex) { 
    ex.printStackTrace(); 
    } 
} 
+0

http://stackoverflow.com/questions/979256/how-to-sort-a-json-array – pramodc84 2011-02-08 06:58:45

回答

2

JSONObject JavaDocs

一個JSONObject是無序 集合名稱/值對。

這意味着你不能自定義排序。如果確實需要自定義排序,包裝各個對象的JSONArray

public void toJSON(String description, String Name){ 
    JSONObject inner = new JSONObject(); 
    JSONObject inner2 = new JSONObject(); 
    JSONObject inner3 = new JSONObject(); 
    JSONArray array = new JSONArray(); 

    try{ 
     array.put(inner); 
     inner.put("description", description); 
     inner.put("filename", imageName); 

     array.put(inner2); 
     inner2.put("model", "modelname"); 

     array.put(inner3); 
     inner3.put("Datetime", "DateTime"); 

     outer.put("values", array); 

    } catch(JSONException ex){ 
     ex.printStackTrace(); 
    } 
}