2016-12-28 55 views
0

在訪問從JSON在斯威夫特3所需的信息,這裏就是我有實際困難:Swift3 JSON解析 - 如何訪問相關領域

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文件在代碼中 - 爲什麼我的代碼沒有返回'data'部分,我如何檢索啤酒'name','abv'和'description'?

+0

'parsedData [「data」]'不是字典,它是一個字典數組。 – Moritz

+0

啊。謝謝@EricAya - 我怎麼才能訪問名字和abv所在的字典? –

+0

這裏有一個例子:http://stackoverflow.com/a/37343547/2227743還有很多其他的例子,這個問題已經被提出並且已經被回答了很多,請做一些研究。 :) – Moritz

回答

0

當你處理JSON我認爲這是有幫助的使用工具,如: jsonformatter.curiousconcept.comjsonlint.com 這幫助了我很多理解結構,什麼樣我處理的數據。

如果你看看你的JSON中,你可以注意到,埃裏克綾說,數據是一個數組沒有字典:

{ 
    "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() 
    } 
+0

謝謝@mat真的很感激它!作品一種享受。還嘗試了另一種方式導入SwiftyJson,然後到達它: using parseddata [data] [0] [abv] 感謝您的幫助! –

+0

@BarronAce很高興聽到它的工作。你能否接受答案,如果它幫助你。謝謝! – mat