2015-10-07 62 views
2

我有一個JSON字符串如下圖所示轉換JSON字符串JSON對象不改變鍵順序

{ 
"college": { 
    "id": "RPD4007", 
    "address": "#302, 1 st cross" 
}, 
"deparment": { 
    "department1": { 
     "name": { 
      "maths": { 
       "chapter": 1, 
       "name": "algebra", 
       "module_id": "01" 
      }, 
      "electronics": { 
       "chapter": 1, 
       "name": "ec", 
       "module_id": "01" 
      } 
     } 
    }, 
    "department2": { 
     "name": { 
      "english": { 
       "chapter": 2, 
       "name": "algebra", 
       "module_id": "02" 
      }, 
      "electrical": { 
       "chapter": 2, 
       "name": "algebra", 
       "module_id": "02" 
      } 
     } 
    } 
} 
} 

我試圖此JSON SRING轉換成JSON對象,

string json_string = EntityUtils.toString(response.getEntity()); 
jObj = new JSONObject(json_string);//json object 
JSONObject object = jobj.getJSONObject("college"); 

但jobj輸出我得到的是與json字符串相反的順序。如下所示,

{ 
"college": { 
    "id": "RPD4007", 
    "address": "#302, 1 st cross" 
}, 
"deparment": { 
    "department2": { 
     "name": { 
      "electrical": { 
       "chapter": 2, 
       "name": "algebra", 
       "module_id": "02" 
      }, 
      "english": { 
       "chapter": 2, 
       "name": "algebra", 
       "module_id": "02" 
      } 
     } 
    }, 
    "department1": { 
     "name": { 
      "electronics": { 
       "chapter": 1, 
       "name": "ec", 
       "module_id": "01" 
      }, 
      "maths": { 
       "chapter": 1, 
       "name": "algebra", 
       "module_id": "01" 
      } 
     } 
    } 
} 
} 

如何以相同的順序得到它它是什麼?

+2

可能[獲取該對象內的對象重複](http://stackoverflow.com/a/4920304) –

+0

可能重複的[JSON順序混合](http://stackoverflow.com/questions/3948206/json-order-mixed-up) – FWeigl

+1

http:///stackoverflow.com/a/4515863/3514144 –

回答

0

這裏的答案:JSON order mixed up

因此,JSON庫可以自由地重新排列元素的順序,因爲他們認爲合適的。這不是一個錯誤。

0

我認爲你做了兩次jsonObject。 就做這樣的事情 你有字符串,其中包含JSON數據 使對象爲你做

string json_string = EntityUtils.toString(response.getEntity()); 
jObj = new JSONObject(json_string);//json object 

然後進行循環使用

String college = jobj.getString("college");