我从 API 返回以下 JSON。在我的数据库中,我已经用 JSON 存储了一个列表。因此,它在 JSON 中为我们提供了一个 JSON 字符串。如何在 Swift 中将它们作为对象访问?更重要的是:如何在 JSON 中解析 JSON?
{
"checklists": [
{
"id": 1,
"account_id": 15,
"user_id": 15,
"object_id": 21,
"checklist": "[{\"title\":\"Test\",\"summary\":\"Test 12\"},{\"title\":\"Test 2 \",\"summary\":\"Test 123\"}]",
"title": "High Altitude Operations",
"type": "other",
"LastHistory": null,
"CleanArray": [
{
"title": "Test",
"summary": "Test 12"
},
{
"title": "Test 2 ",
"summary": "Test 123"
}
]
}
]
}
最佳答案
首先,解码主要对象。
假设 data
是您问题中的 JSON:
let json = JSON(data: data)
要获取 checklists
键内数组中 checklist
键的内容,我们可以像这样使用 SwiftyJSON 的键路径下标:
let checkList = json["checklists",0,"checklist"]
print(checkList)
打印:
[{"title":"Test","summary":"Test 12"},{"title":"Test 2 ","summary":"Test 123"}]
这是作为字符串的内部 JSON。
让它成为数据,然后做同样的过程并访问数组内容:
if let json2String = checkList.string,
data2 = json2String.dataUsingEncoding(NSUTF8StringEncoding) {
let json2 = JSON(data: data2)
let checkList2 = json2[0]
let title = checkList2["title"]
print(title)
}
打印:
Test
请注意,我在此示例中使用了关键路径下标,但简单下标、循环和 map/flatMap/等常用技术也有效:
let mainChecklists = json["checklists"]
for (_, content) in mainChecklists {
if let innerString = content["checklist"].string,
data2 = innerString.dataUsingEncoding(NSUTF8StringEncoding) {
let json2 = JSON(data: data2)
for (_, innerChecklist) in json2 {
let title = innerChecklist["title"]
print(title)
}
}
}
打印:
Test
Test 2
关于swift - 如何使用 SwiftyJSON 解析 Json 中的 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423950/