我正在尝试解析通过API调用获得的一些JSON数据。我首先尝试了艰难的方法:没有库。当这不起作用时,我尝试了SwiftyJSON,但这也没有多大帮助。我正试图从啤酒中获取所有子信息。
在这里你可以看到我打印出整个JSON'对象'的位置。
夫特
let json = JSON(data: JSONData)
print(json);
输出
{
"meta" : {
"init_time" : {
"measure" : "seconds",
"time" : 0.011
},
"response_time" : {
"measure" : "seconds",
"time" : 0.056
},
"code" : 200
},
"notifications" : [
],
"response" : {
"macro" : {
"count" : 10,
"items" : [
{
"beer" : {
"wish_list" : false,
"beer_abv" : 5.4,
"auth_rating" : 0,
"style_name" : "Witbier",
"beer_label" : "https:\/\/untappd.akamaized.net\/site\/beer_logos\/beer-3839_207a3_sm.jpeg",
"bid" : 3839,
"beer_name" : "Belgian White",
"beer_style" : "Witbier"
},
"total_count" : 668,
"your_count" : 0,
"brewery" : {
"location" : {
"lng" : -104.992,
"lat" : 39.7561,
"brewery_city" : "Denver",
"brewery_state" : "CO"
},
"brewery_name" : "Blue Moon Brewing Company",
"brewery_slug" : "blue-moon-brewing-company",
"brewery_id" : 127804,
"country_name" : "United States",
"brewery_label" : "https:\/\/untappd.akamaized.net\/site\/brewery_logos\/brewery-127804_1a670.jpeg",
"contact" : {
"twitter" : "BlueMoonBrewCo",
"facebook" : "https:\/\/www.facebook.com\/bluemoon",
"url" : "http:\/\/www.bluemoonbrewingcompany.com\/",
"instagram" : ""
},
"brewery_active" : 1
}
},
这里我详细介绍了子级别。
夫特
let json = JSON(data: JSONData)
let list = json["response","micro","items"]
print(list)
输出
[
{
"beer" : {
"wish_list" : false,
"beer_abv" : 4.7,
"auth_rating" : 0,
"style_name" : "IPA - Session \/ India Session Ale",
"beer_label" : "https:\/\/untappd.akamaized.net\/site\/beer_logos\/beer-36834_82ca8_sm.jpeg",
"bid" : 36834,
"beer_name" : "All Day IPA",
"beer_style" : "IPA - Session \/ India Session Ale"
},
"total_count" : 548,
"your_count" : 0,
"brewery" : {
"location" : {
"lng" : -85.6735,
"lat" : 42.9585,
"brewery_city" : "Grand Rapids",
"brewery_state" : "MI"
},
"brewery_name" : "Founders Brewing Co.",
"brewery_slug" : "founders-brewing-co",
"brewery_id" : 549,
"country_name" : "United States",
"brewery_label" : "https:\/\/untappd.akamaized.net\/site\/brewery_logos\/brewery-foundersbrewingcompany_549.jpeg",
"contact" : {
"twitter" : "foundersbrewing",
"facebook" : "http:\/\/www.facebook.com\/foundersbrewing",
"url" : "http:\/\/www.foundersbrewing.com\/",
"instagram" : "foundersbrewing"
},
"brewery_active" : 1
}
},
当我加入“啤酒”时。我得到了一个“空” - 回复。我认为不是因为括号的不同。 “[]”= list和“{}”= dictionaire。但我仍然无法解决它。
(我不是iOS开发人员,只是第一次与swift3交互的学生)
夫特
let json = JSON(data: JSONData)
let list = json["response","micro","items","beer"]
print(list)
输出
null
答案 0 :(得分:2)
您可以像这样使用SwiftyJSON解析响应对象。而你的items
对象就是一系列啤酒。希望你能得到你的想法。
let json = JSON(data: JSONData)
let list = json["response"]["micro"]["items"].arrayValue
for beerObjects in list {
// You can get sub info of beer like this.
let beer_name = beerObjects["beer"]["beer_name"].stringValue
let total_count = beerObjects["total_count"].intValue
let brewery_city = beerObjects["brewery"]["location"]["brewery_city"]
// or parse information which you need
}