如何使用 SwiftyJSON 在 Json 中解析 Json? [英] How Can I Parse Json In Json With SwiftyJSON?

查看:63
本文介绍了如何使用 SwiftyJSON 在 Json 中解析 Json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 API 返回以下 JSON.在我的数据库中,我已经在 J​​SON 中存储了一个列表.因此,它在 JSON 中为我们提供了一个 JSON 字符串.如何在 Swift 中将这些作为对象访问?更重要的是:如何在 JSON 中解析 JSON?

I am returning the following JSON from an API. In my database, I store a list in JSON already. Thus, it gives us a string of JSON inside JSON. How can I access these as objects in Swift? More to the point: How can I parse JSON inside of 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's say data is the JSON in your question:

let json = JSON(data: data)

要获取checklists键内数组中checklist键的内容,我们可以像这样使用SwiftyJSON的键路径下标:

To get the content of the checklist key inside the array inside the checklists key, we can use SwiftyJSON's key path subscripting like this:

let checkList = json["checklists",0,"checklist"]
print(checkList)

打印:

[{"title":"Test","summary":"Test 12"},{"title":"Test 2","summary":"Test 123"}]

[{"title":"Test","summary":"Test 12"},{"title":"Test 2 ","summary":"Test 123"}]

这是作为字符串的内部 JSON.

This is your inner JSON as a String.

将其设为数据,然后执行相同的过程并访问数组内容:

Make it data, then do the same process and access the array content:

if let json2String = checkList.string, 
        data2 = json2String.dataUsingEncoding(NSUTF8StringEncoding) {
    let json2 = JSON(data: data2)
    let checkList2 = json2[0]
    let title = checkList2["title"]
    print(title)
}

打印:

测试

请注意,我在此示例中使用了键路径下标,但简单下标、循环和 map/flatMap/etc 等常用技术也可以使用:

Note that I've used key path subscripting for this example, but usual techniques like simple subscripting, loops and map/flatMap/etc also work:

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)
        }
    }
}

打印:

测试
测试 2

这篇关于如何使用 SwiftyJSON 在 Json 中解析 Json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆