webentwicklung-frage-antwort-db.com.de

Analysieren Sie die JSON-Antwort mit Swift 3

Ich habe JSON so aussehen:

{"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
}

Wie kann ich diese JSON mit Swift 3 analysieren?

Ich habe das:

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()
}
10
user3051755

Verwenden Sie dies, um Ihre Daten zu analysieren:

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()

Verwenden Sie guard, um zu prüfen, ob Sie Daten haben und der Fehler leer ist.

17
Rashwan L

In Swift 3.0 für die GET-Methode:

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 für die Methode POST:

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()

Weil Ihre Datenstruktur von test json "[String: AnyObject]" sein sollte. Der json-Schlüssel "posts" ist der Array-Typ.

0
user6911979