我想在这个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"
}
]
}
}
}
首先,我已经创建了我的People结构,用于从那些JSON映射。 这是我的人员结构
struct People {
var peopleLooks:String?
var name:String?
var books = [Book]()
}
这是我的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.
}
我的问题是,如何将peoples
从jsonRecieve["People"]
映射到我的结构中?
我希望在"People with nice hair"
结构中将peopleLooks
作为People
的值。我认为"People with nice hair"
是词典或其他东西的关键,但我不知道如何得到它。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:4)
在迭代字典时,例如
for peeps in peoples
您可以使用
访问密钥peeps.0
和
的值peeps.1
答案 1 :(得分:3)
您可以使用键值循环。
for (key,subJson):(String, JSON) in json["People"] {
// you can use key and subJson here.
}