如何使用 SwiftyJSON 解析 Json In Json?
How Can I Parse Json In Json With SwiftyJSON?
我从 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/etc 等常用技术也有效:
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
我从 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/etc 等常用技术也有效:
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