2016-08-15 56 views
1

我想「詞典的鑰匙」(這就是我所謂的,不知道這是否是正確的名稱)這個JSON獲取字典的關鍵在JSON解析與SwiftyJSON

{ 
    "People": { 
    "People with nice hair": { 
     "name": "Peter John", 
     "age": 12, 
     "books": [ 
     { 
      "title": "Breaking Bad", 
      "release": "2011" 
     }, 
     { 
      "title": "Twilight", 
      "release": "2012" 
     }, 
     { 
      "title": "Gone Wild", 
      "release": "2013" 
     } 
     ] 
    }, 
    "People with jacket": { 
     "name": "Jason Bourne", 
     "age": 15, 
     "books": [ 
     { 
      "title": "Breaking Bad", 
      "release": "2011" 
     }, 
     { 
      "title": "Twilight", 
      "release": "2012" 
     }, 
     { 
      "title": "Gone Wild", 
      "release": "2013" 
     } 
     ] 
    } 
    } 
} 

首先,我已經創建了我的人員結構,將用於從這些JSON映射。 這裏是我的人結構

struct People { 
    var peopleLooks:String? 
    var name:String? 
    var books = [Book]() 
} 

這裏是我的書結構

struct Book { 
    var title:String? 
    var release:String? 
} 

從這個JSON,我創建了Alamofire和SwiftyJSON引擎,會在我的控制器通過完成處理程序被稱爲

Alamofire.request(request).responseJSON { response in 
    if response.result.error == nil { 
     let json = JSON(response.result.value!) 
     success(json) 
    } 
} 

這裏是我在我的控制器中做的事

Engine.instance.getPeople(request, success:(JSON?)->void), 
    success:{ (json) in 

    // getting all the json object 
    let jsonRecieve = JSON((json?.dictionaryObject)!) 

    // get list of people 
    let peoples = jsonRecieve["People"] 

    // from here, we try to map people into our struct that I don't know how. 
} 

我的問題是,如何將我的peoplesjsonRecieve["People"]映射到我的結構? 我想要"People with nice hair"作爲peopleLooks的值在我的People結構。我認爲"People with nice hair"是字典或其他東西的關鍵,但我不知道如何得到它。

任何幫助,將不勝感激。謝謝!

回答

2

當你在字典中循環,例如

for peeps in peoples 

您可以

peeps.0 

和價值訪問鍵與

peeps.1 
+1

Yeaaaahh,你救了我的一天!謝謝soooo,@NickCatib!將在幾分鐘內批准此答案。 –

1

對於短暫嘗試下面的代碼(我用swift 2.0沒有第三方)

Engine.instance.getPeople(request, success:(JSON?)->void), 
    success:{ (json) in 

    // getting all the json object 
    let jsonRecieve = JSON((json?.dictionaryObject)!)   
     print(jsonRecieve) 

    let extract1 = jsonRecieve["People"] 
    print(extract1) 

    let extract2 = extract1!!["People with nice hair"] 
    print(extract2) 

    let getbooks = extract2!!["books"] as? [[String:AnyObject]] 
    print(getbooks) 

    for books in getbooks! 
    { 
     let title = books["title"] as! String 
     let release = books["release"] as! String 
     print("\n"+title+"\n"+release) 
    } 
} 

Swift對於JSON很靈活。所以,我們不需要第三方庫。如果你混淆瞭解析JSON而沒有第三方庫,那麼see my videos。我給你:) :):D

+0

是的,你可以使用它作爲字典沒有任何問題,但與你的代碼的問題是,這是不可擴展的 - 你硬編碼提取1的關鍵!! [「頭髮很好的人」]。我的解決方案是在字典上工作,所以不是extract2,而是遍歷字典,然後使用密鑰。 – Miknash

+0

哎!但它工作正常,沒有任何警告。那麼,我如何遍歷字典呢?感謝您的有用信息:D :) –

+0

簡單應該做的工作:)這不是與警告的問題,但未來的驗證碼 – Miknash