简体   繁体   English

在Java中构造JSON对象并从JSONObject获取值

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

i'm new to JSON 我是JSON新手

1. i got json result in html in following format 1.我得到了html格式的json结果,格式如下

JSon Result 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 . 2 how do i get such format with java code JSONObject is Resorts is key of map ? 如何使用Java代码JSONObject获得这样的格式,Resorts是map的键?

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

Be careful. 小心。 If the json to the variable "result" is in your second code block, you can't expect to find any data by using "result.resort0" or "result.resort1". 如果变量“ result”的json在第二个代码块中,则不能期望使用“ result.resort0”或“ result.resort1”来查找任何数据。 In your example, result contains a submember called "Resorts" which holds an array of submembers. 在您的示例中,结果包含一个名为“ Resorts”的子成员,该子成员包含一个子成员数组。

In other words, to cycle through all values, I would expect javascript like: 换句话说,要遍历所有值,我希望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