如何解析Swift中包含Objects的JSON数组

时间:2016-07-27 07:27:51

标签: arrays json swift parsing nested

我有一个JSON响应,它似乎由多个对象组成,我无法解析它们,并且在我尝试访问对象内的字段时始终为nil。

我如何解析例如内部对象的字段名称"结果"?

JSON对象:

{
result =     (
            {
        "cor_date" = "2016-01-04";
        "cor_id" = 24003;
        "course_type" = C;
        duration = 52;
        name = "Combined Course";
        "sco_id" = 24;
        status = ACT;
    },
            {
        "cor_date" = "2016-01-04";
        "cor_id" = 24002;
        "course_type" = C;
        duration = 52;
        name = "Intensive Course";
        "sco_id" = 24;
        status = ACT;
    }
);
}

我在这里尝试使用此代码来解析上面的JSON响应并访问单个字段:

let response = responseObject as? [String:AnyObject] //this works here
    print("response")
    print(response) 
    let resp2 = response!["result"]  as? [String:AnyObject]  // this results in nil
    print("resp2")
    print(resp2)

    if let response = responseObject as? [String:AnyObject] {
        if let result = response["result"] as? [String:AnyObject] {
            // work with the content of "result", for example:
            if let displayName = result["name"] {
                print("print display name of course")
                print(displayName)
            }
        } else {
            // handle the failure to decode
        }
    }

我从控制台的print命令获得了以下repsones:

response
Optional(["result": <__NSCFArray 0x7f9db0c86790>(
{
"cor_date" = "2016-01-04";
"cor_id" = 24003;
"course_type" = C;
duration = 52;
name = "Combined Course";
"sco_id" = 24;
status = ACT;
},
{
"cor_date" = "2016-01-04";
"cor_id" = 24002;
"course_type" = C;
duration = 52;
name = "Intensive Course";
"sco_id" = 24;
status = ACT;
}
)
])


resp2
nil

1 个答案:

答案 0 :(得分:-1)

此代码执行此操作:

//parse down the first layer of array
     let response = responseObject as? [String:AnyObject]
    print("response")
    print(response)

    //parse down the second layer of JSON object
    if let result = response!["result"]  as? [AnyObject] {

            // work with the content of "result", for example:
            if let displayName = result[0] as? [String:AnyObject]{
                print(displayName)

                let courseName = displayName["name"]
                print("courseName")
                print(courseName)
        }