如何使用Swift 3解析复杂的JSON数据结构

时间:2017-10-20 21:46:55

标签: json swift parsing dictionary

我试图解析从包含项目资源信息的URLSession返回的这个JSON数据结构。尽管有许多方法没有达到我需要访问数据的水平。

具体来说,我需要获取计划者角色的作业状态,即r:和JSON中s:的状态。

所以我认为我需要遍历所有值以查找计划员角色的状态,或者是否有办法指定我正在寻找计划者并直接能够为其检索状态?

我不确定如何遍历它以达到这个级别,这个问题的一个有趣但具有挑战性的部分是资源有三个值,所以我不认为字典键价值对是正确的模式。

{
  "Project": 43,
  "definition": [
    {
      "statusCode": 0,
      "entryID": "123",
      "Initiatives": [],
      "validationCode": "1.0.0"
    },
    {
      "statusCode": 0,
      "workProduct": [
        {
          "task": [
            {
              "desc": "define project scope",
              "hours": 120,
              "week": "1",
              "resources": [
                {
                  "r": "planner",
                  "l": "junior",
                  "s": "open"
                },
                {
                  "r": "architect",
                  "s": "senior",
                  "s": "filled"
                }
              ],
              "managerCode": "1285",
              "teamCode": [
                "413"
              ]
            }
          ],
          "scope": "project design"
        }
      ],
      "entryID": "123",
      "validationCode": "1.0.0"
    }
  ]
}

根据各种SO答案和article我已经尝试了多种尝试访问它的解决方案:

我可以将JSON对象打印为字符串:

let stringData = String(data: projectInformation!, encoding: String.Encoding.utf8)
            print(stringData as Any) //JSONSerialization

但我不确定这是检索它的值的最佳方式。

绝对感谢您的建议。

2 个答案:

答案 0 :(得分:0)

这会很混乱。

do{
  let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]

  if let project = json["Project"] as? Int {
    //do something
  }
  if let definition = json["definition"] as? [DefinitionType] {
    // do something
  }
} catch {
  //error
}

制作初始化程序init(json: [String: Any])

使用其他第三方库

https://github.com/SwiftyJSON/SwiftyJSON

答案 1 :(得分:-1)

刚刚开始,但应该让你滚动。我解析它直到workProduct

let object = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let dictionaryItem = object["definition"]![1] as! [String: AnyObject]
let workProductItems = dictionaryItem["workProduct"]

这产生了这样的结果:

{
    scope = "project design";
    task =     (
                {
            desc = "define project scope";
            hours = 120;
            managerCode = 1285;
            resources =             (
                                {
                    l = junior;
                    r = planner;
                    s = open;
                },
                                {
                    r = architect;
                    s = senior;
                }
            );
            teamCode =             (
                413
            );
            week = 1;
        }
    );
}
)
, "validationCode": 1.0.0]

继续解析,直到得到你想要的东西。

相关问题