2017-07-07 14 views
3

swift(PHP接続)内でJSON結果を読み込む際に問題があります。SwiftがJSON結果から変数を割り当てていません

JSONデータを取得できますが、変数に割り当てることはできません。

常に結果はOptionalと割り当てられます。

JSONデータ:

{ 
"country": [{ 
    "id": 1, 
    "name": "Australia", 
    "code": 61 
}, { 
    "id": 2, 
    "name": "New Zealand", 
    "code": 64 
}] 
} 

Xcodeの出力:

["country": <__NSArrayI 0x60000002da20>(
{ 
    code = 61; 
    id = 1; 
    name = Australia; 
}, 
{ 
    code = 64; 
    id = 2; 
    name = "New Zealand"; 
} 
) 
] 
Country Name: Optional(Australia) 
Country Name: Optional(New Zealand) 

.swiftファイル:

//function did_load 
override func viewDidLoad() { 
    super.viewDidLoad() 

    //created RequestURL 
    let requestURL = URL(string: get_codes) 

    //creating NSMutable 
    let request = NSMutableURLRequest(url: requestURL!) 

    //setting the method to GET 
    request.httpMethod = "GET" 

    //create a task to get results 
    let task = URLSession.shared.dataTask(with: request as URLRequest) { 
     data, response, error in 

     if error != nil{ 
      print("error is \(String(describing: error))") 
      return; 
     } 

     //lets parse the response 
     do { 
      let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any] 
      print(json) 
      if let countries = json["country"] as? [[String: AnyObject]] { 
       for country in countries { 
        print("Country Name: \(String(describing: country["name"]))") 
        print("Country Code: \(String(describing: country["code"]))") 
        if let couname = country["name"] as? [AnyObject] { 
         print(couname) 
        } 

        if let coucode = country["code"] as? [AnyObject] { 
         print(coucode) 
        } 
       } 
      } 
     } catch { 
      print("Error Serializing JSON: \(error)") 
     } 
    } 
    //executing the task 
    task.resume() 
} 
+0

辞書添字は、オプションを返し、例えばhttps://stackoverflow.com/questions/25979969/println-dictionary-has-optional(またはスウィフト言語参照)を参照してください。 'country [" name "]は? [AnyObject] 'は値が配列ではなく文字列であるため意味をなさない。 –

+1

'String(describe:)'は、ほとんどあなたが望むものではなく、実際の型の問題を隠すことに注意してください。 –

+0

推奨読書:https://developer.apple.com/swift/blog/?id=37とhttps://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3 –

答えて

3

あなたは文字列補間で使用する前にオプションのラップを解除する必要があります。これを行う最も安全な方法は、オプションのバインドによるものです。

以下のコードを使用してください。

if let countries = json["country"] as? [[String: AnyObject]] { 
      for country in countries { 
       print("Country Name: \(country["name"] as! String)") 
       print("Country Code: \(country["code"] as! String)") 
       if let couname = country["name"] as? String { 
        print(couname) 
       } 

       if let coucode = country["code"] as? Int { 
        print(coucode) 
       } 
      } 
     } 
+0

これは次のエラーをスローします: "未解決の識別子 '応答'の使用" – BarryWhite

+0

json –

+0

さんとの応答を置き換えてください - あなたは完全に編集しました! – BarryWhite

関連する問題