2016-12-03 37 views
0

以下是JSON結果我被使用JSON解析與SWIFT 3中提取數據

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 

得到,但我無法從數據中提取標題,author_data [「名稱」] &摘要。

我想將數據存儲在局部變量中。我該怎麼做?

JSON結果:

{ 
"current_page" = 1; 
data =  (
      { 
     "author_data" =    (
          { 
       id = "kiyosaki_robert_t"; 
       name = "Kiyosaki, Robert T."; 
      } 
     ); 
     "awards_text" = ""; 
     "book_id" = "rich_dads_the_business_school_a01"; 
     "dewey_decimal" = ""; 
     "dewey_normal" = 0; 
     "edition_info" = "Hardcover; 2008-08-30"; 
     isbn10 = 8186775811; 
     isbn13 = 9788186775813; 
     language = ""; 
     "lcc_number" = ""; 
     "marc_enc_level" = "~"; 
     notes = ""; 
     "physical_description_text" = "6.1\"x9.1\"x0.4\"; 0.4 lb"; 
     "publisher_id" = "manjul_publishing_house_pvt_lt"; 
     "publisher_name" = "Manjul Publishing House Pvt Ltd"; 
     "publisher_text" = "Manjul Publishing House Pvt Ltd"; 
     "subject_ids" =    (
      "business_investing_general" 
     ); 
     summary = "Presents eight hidden values of a network marketing business. This book is suitable for those associated with network marketing."; 
     title = "Rich Dad's the Business School"; 
     "title_latin" = "Rich Dad's the Business School"; 
     "title_long" = ""; 
     "urls_text" = ""; 
    } 
); 
"index_searched" = isbn; 
"page_count" = 1; 
"result_count" = 1; 
} 

回答

0

您可以從Dictionary如果你用斯威夫特本地字典,而不是NSDictionary也與本地字典裏沒有需要指定mutableContainers選項輕鬆地訪問數據。現在你的dataDictionaryauthor_data的陣列是data的第一個Dictionary陣列,你可以像這樣得到它的名字。

if let jsonDic = try? JSONSerialization.jsonObject(with: urlContent, options: []) as? [String:Any] { 
    if let dataArray = jsonDic["data"] as? [[String:Any]], let firstObj = dataArray.first { 
     if let summary = firstObj["summary"] as? String, 
      let author_data = firstObj["author_data"] as? [[String:Any]], 
      let authorObj = author_data.first, 
      let name = authorObj["name"] { 
      print(summary) 
      print(name) 
     } 
    } 
}