繁体   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