简体   繁体   中英

Get key of dictionary on JSON parse with SwiftyJSON

I want to get "key of dictionary" (that's what I called, not sure if it is right name) on this JSON

{
  "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"
        }
      ]
    }
  }
}

First of all, I already created my People struct that will be used to map from those JSON. Here is my people struct

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

And here is my Book struct

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

From that JSON, I created engine with Alamofire and SwiftyJSON that will be called in my controller via completion handler

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

And here is what I do in my controller

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.
}

My question is, how to map my peoples from jsonRecieve["People"] into my struct? I want "People with nice hair" as a value of peopleLooks on my People struct. I thought "People with nice hair" is kind of key of dictionary or something, but I don't know how to get that.

Any help would be appreciated. Thank you!

While you iterate through dictionaries, for instance

for peeps in peoples

You can access key with

peeps.0

and value with

peeps.1

You can use key, value loop.

for (key,subJson):(String, JSON) in json["People"] {
   // you can use key and subJson here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM