2011-05-16 54 views
1
獲得價值

我是新來的JSON構建JSON對象,並從JSONObject的

我得到JSON結果以HTML的格式如下

JSON結果

Alert(result) 
{"resort0":"Abaco Beach Resort at Boat Harbour","resort1":"Alexandra Resort","room0":"1 Bedroom Luxury Oceanfront Suite","room1":"2 Bedroom Deluxe Ocean View Suite","room2":"Deluxe Garden View Studio","room3":"Deluxe Ocean View Studio","room4":"Deluxe Oceanfront","room5":"Oceanfront","room6":"Superior Oceanfront"} 

alert(result.resort1); // alert "undefined" 
alert(result.resort0); // alert "undefined" 

。我如何獲得這樣的格式與Java代碼JSONObject 是度假村是地圖的關鍵?

{ 
      "Resorts" : [ 
        { "name"  : "Resort1", // First element 
         "room1"  : "rooms1" 
         "room2"  : "rooms2" }, 
        { "name"  : "Resort2", // Second element 
         "room1"  : "rooms1", 
         "room2"  : "rooms2", } 
       ] 
} 

回答

2

要小心。如果變量「result」的json位於第二個代碼塊中,則不能期望通過使用「result.resort0」或「result.resort1」來查找任何數據。在你的例子中,結果包含一個名爲「Resorts」的子成員,其中包含一系列子成員。

換句話說,通過所有的值週期,我希望類似的JavaScript:

for(var i=0; i<result.Resorts.length; i++) { 
    alert(result.Resorts[i].name); 
    alert(result.Resorts[i].room1); 
    alert(result.Resorts[i].room2); 
}