我正在尝试循环使用此JSON示例,以使用SwiftyJSON获取age
,name
和type
。我成功获得name
和age
,但type
对我来说很难。有人可以告诉我该怎么做,拜托?
"both": [
{
"id": 130,
"name": "TMT",
"age": "2006",
"created_at": "2016-12-19 21:37:06",
"updated_at": "2016-12-19 21:37:06",
"pic": "1482183426.png",
"pivot": {
"user_id": 4,
"car_id": 130,
"type": "rent"
}
},
{
"id": 113,
"name": "TMT ",
"age": 2016,
"created_at": "2016-12-18 14:46:18",
"updated_at": "2016-12-18 14:47:41",
"pic": "",
"pivot": {
"user_id": 4,
"car_id": 113,
"type": "rent"
}
}
]
工作
let json = JSON(value)
for (key, subJson) in json {
let cars = subJson["both"]
for (key, subJson) in cars {
print(subJson["age"])
}
答案 0 :(得分:3)
您只需访问pivot
字典并从那里阅读type
密钥。
let json = JSON(value)
for (key, subJson) in json {
let cars = subJson["both"]
for (key, subJson) in cars {
let age = subJson["age"]
// Access pivot dictionary
let pivot = subJson["pivot"]
// Get type from pivot dictionary
let type = pivot["type"]
}
}