web-dev-qa-db-ja.com

Swift 3でJSONレスポンスを解析

私はこのように見えるJSONを持っています:

{"posts":
    [
    {
    "id":"1","title":"title 1"
    },
    {
    "id":"2","title":"title 2"
    },
    {
    "id":"3","title":"title 3"
    },
    {
    "id":"4","title":"title 4"
    },
    {
    "id":"5","title":"title 5"
    }
    ],
    "text":"Some text",
    "result":1
}

Swift 3でJSONを解析するにはどうすればよいですか?

私はこれを持っています:

let url = URL(string: "http://domain.com/file.php")!
let request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else {
        print("request failed \(error)")
            return
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
            // Parse JSON
        }
    } catch let parseError {
        print("parsing error: \(parseError)")
        let responseString = String(data: data, encoding: .utf8)
            print("raw response: \(responseString)")
        }
    }
    task.resume()
}
11
user3051755

これを使用してデータを解析します。

let url = URL(string: "http://domain.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
    guard let data = data, error == nil else { return }

    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        let posts = json["posts"] as? [[String: Any]] ?? []
        print(posts)
    } catch let error as NSError {
        print(error)
    }
}).resume()

guardを使用して、データがあり、エラーが空かどうかを確認します。

21
Rashwan L

In Swift 3.0 GETメソッドの場合:

var request = URLRequest(url: URL(string: "Your URL")!)        

    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()

In Swift 3.0 for POST method:

var request = URLRequest(url: URL(string: "Your URL")!)

    request.httpMethod = "POST"
    let postString = "user_name=ABC"  // Your parameter
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()

テストJSONのデータ構造は「[String:AnyObject]」である必要があるためです。 jsonキーの「投稿」値は配列型です。

0
user6911979