Swift3 Json Parsing - 如何访问相关字段
Posted
技术标签:
【中文标题】Swift3 Json Parsing - 如何访问相关字段【英文标题】:Swift3 Json Parsing - how to access relevant fields 【发布时间】:2016-12-28 00:00:36 【问题描述】:在从 JSON 访问 Swift 3 中所需的信息时遇到了真正的困难,这就是我所拥有的:
override func viewDidLoad()
super.viewDidLoad()
let url = URL(string: "http://api.brewerydb.com/v2/beers?key=e3bdce7d0a80584c784cdc4b02459add&name=budweiser")
URLSession.shared.dataTask(with:url!) (data, response, error) in
if error != nil
print(error!)
else
do
let parsedData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
// print(parsedData)
let dataLevel = parsedData["data"] as? NSDictionary
print(dataLevel)
let abv = dataLevel?["abv"] as? AnyObject
print(abv!)
catch let error as NSError
print(error)
.resume()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
JSON 文件的链接在代码中 - 为什么我的代码没有返回“数据”部分,我如何检索啤酒的“名称”、“abv”和“描述”?
【问题讨论】:
parsedData["data"]
不是字典,而是字典数组。
啊。谢谢@EricAya - 那么我如何访问 name 和 abv 所在的字典?
这里有一个例子:***.com/a/37343547/2227743 还有很多其他的例子,这个问题已经被问过很多次了,请做一些研究。 :)
【参考方案1】:
当您处理 JSON 时,我认为使用以下工具会很有帮助: jsonformatter.curiousconcept.com 或者 jsonlint.com 这有助于我理解结构和我正在处理的数据类型。
如果您查看您的 json,您会注意到,正如 Eric Aya 所说,数据是一个数组而不是字典:
"currentPage": 1,
"numberOfPages": 1,
"totalResults": 1,
"data": [
"id": "1P45iR",
"name": "Budweiser",
"nameDisplay": "Budweiser",
"description": "Known as \u201cThe King of Beers\u201d, Budweiser was first introduced by Adolphus Busch in 1876 and is brewed with the same high quality standards today. Budweiser is a medium-bodied, flavorful, crisp American-style lager, craft brewed with a blend of premium hop varieties, and associated with the core American values of celebration and optimism.",
"abv": "5",
"glasswareId": 5,
"srmId": 5,
"availableId": 1,
"styleId": 93,
"isOrganic": "N",
"labels":
"icon": "https:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/1P45iR\/upload_Y13vwL-icon.png",
"medium": "https:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/1P45iR\/upload_Y13vwL-medium.png",
"large": "https:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/1P45iR\/upload_Y13vwL-large.png"
,
"status": "verified",
"statusDisplay": "Verified",
"servingTemperature": "cold",
"servingTemperatureDisplay": "Cold - (4-7C\/39-45F)",
"createDate": "2012-01-03 02:42:55",
"updateDate": "2016-03-21 19:54:11",
"glass":
"id": 5,
"name": "Pint",
"createDate": "2012-01-03 02:41:33"
,
"srm":
"id": 5,
"name": "5",
"hex": "FBB123"
,
"available":
"id": 1,
"name": "Year Round",
"description": "Available year round as a staple beer."
,
"style":
"id": 93,
"categoryId": 8,
"category":
"id": 8,
"name": "North American Lager",
"createDate": "2012-03-21 20:06:46"
,
"name": "American-Style Lager",
"shortName": "American Lager",
"description": "Light in body and very light to straw in color, American lagers are very clean and crisp and aggressively carbonated. Flavor components should b e subtle and complex, with no one ingredient dominating the others. Malt sweetness is light to mild. Corn, rice, or other grain or sugar adjuncts are often used. Hop bitterness, flavor and aroma are negligible to very light. Light fruity esters are acceptable. Chill haze and diacetyl should be absent.",
"ibuMin": "5",
"ibuMax": "13",
"abvMin": "3.8",
"abvMax": "5",
"srmMin": "2",
"srmMax": "4",
"ogMin": "1.04",
"fgMin": "1.006",
"fgMax": "1.01",
"createDate": "2012-03-21 20:06:46",
"updateDate": "2015-04-07 15:39:26"
],
"status": "success"
以下代码有效,但我确信有更好的方法可以用更少的代码获得abv
:
override func viewDidLoad()
super.viewDidLoad()
let url = URL(string: "http://api.brewerydb.com/v2/beers?key=e3bdce7d0a80584c784cdc4b02459add&name=budweiser")
URLSession.shared.dataTask(with:url!) (data, response, error) in
if error != nil
print(error!)
else
do
let parsedData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]
let jsonArrayData = parsedData?["data"] as! NSArray
let data = jsonArrayData[0] as! NSDictionary
let abv = data["abv"]
print(abv)//Optional(5) in your case
catch let error as NSError
print(error)
.resume()
【讨论】:
感谢@mat 非常感谢!工作一种享受。还尝试了导入 SwiftyJson 的另一种方式,然后通过以下方式得到它: using parseddata[data][0][abv] 感谢您的帮助! @BarronAce 很高兴听到它有效。如果对您有帮助,请您接受答案。谢谢!以上是关于Swift3 Json Parsing - 如何访问相关字段的主要内容,如果未能解决你的问题,请参考以下文章
Android Retrofit Json Parsing(部分json动态)
Unexpected end of JSON input while parsing near
Objc live Json Parsing Only 显示 1 项错误
如何将 JSON 数据存储到 swift3 中的数组(模型类)中?
npm install出现"Unexpected end of JSON input while parsing near"错误解决方法