2016-08-15 67 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