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()
}
辞書添字は、オプションを返し、例えばhttps://stackoverflow.com/questions/25979969/println-dictionary-has-optional(またはスウィフト言語参照)を参照してください。 'country [" name "]は? [AnyObject] 'は値が配列ではなく文字列であるため意味をなさない。 –
'String(describe:)'は、ほとんどあなたが望むものではなく、実際の型の問題を隠すことに注意してください。 –
推奨読書:https://developer.apple.com/swift/blog/?id=37とhttps://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3 –