2016-07-27 10 views
0

JSONレスポンスは、複数のオブジェクトで構成されているように見えますが、それらの解析に失敗し、オブジェクト内のフィールドにアクセスしようとすると常にnilになります。Swiftでオブジェクトが内部にあるJSON配列を解析する方法

「結果」内にあるオブジェクトのフィールド名などを解析するにはどうすればよいですか?

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

このコードでは:

//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) 
     } 
関連する問題