簡體   English   中英

在Java中構造JSON對象並從JSONObject獲取值

[英]construct json Object in java and get value from JSONObject

我是JSON新手

1.我得到了html格式的json結果,格式如下

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"

2 如何使用Java代碼JSONObject獲得這樣的格式,Resorts是map的鍵?

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

小心。 如果變量“ 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM