swift - 如何使用 SwiftyJSON 解析 Json 中的 Json?

标签 swift swifty-json

我从 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/

相关文章:

swifty-json - swiftyjson 无法将原始字符串转换回 json 对象

ios - 转换为 Xcode 7 后 Alamofire + SwiftyJSON 编译错误

ios - JSON 到多维数组

ios - 如何从多维数组中过滤内部数组

swift - Alamofire 多参数(查询和表单)Swift 4

ios - 检查对象是否超出数组范围的最佳方法

arrays - 对数组索引使用 switch/case

swift - 无法调用非函数类型的值 'HTTPURLResponse?' - Alamofire 4.0

ios - PHImageManager 是否为 2x 和 3x 屏幕返回像素或点大小的图像?

ios - UIDocumentPickerViewController - 未调用委托(delegate)方法