Разбор ответа JSON с помощью Swift 3

У меня 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
}

Как я могу разобрать этот JSON с помощью Swift 3?

у меня есть это:

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

4 ответов


используйте это для анализа данных:

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 чтобы проверить, есть ли у вас данные, и эта ошибка пуста.


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

в swift 3.0 для метода 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()

потому что ваша структура данных тестового json должна быть "[String: AnyObject]". Значение ключа JSON "posts" - это тип массива.


РАССТОЯНИЕ--СЛОЖНЫЙ API ========================>

class ViewController: UIViewController {

    var get_data = NSMutableData()

    var get_dest = NSArray()

    var org_add = NSArray()

    var row_arr = NSArray()



    var ele_arr = NSArray()

    var ele_dic = NSDictionary()

    var dist_dic = NSDictionary()

    var dur_dic = NSDictionary()

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        getmethod()

    }



    func getmethod()

    {

        let url_str = URL(string: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&departure_time=1408046331&origins=37.407585,-122.145287&destinations=37.482890,-122.150235")

        let url_req = URLRequest(url: url_str!)

        let task = URLSession.shared.dataTask(with: url_req) { (data, response, error) in

            if let my_data = data

            {

               print("my data is----->",my_data)

                do

                {

                    self.get_data.append(my_data)

                    let jsondata = try JSONSerialization.jsonObject(with: self.get_data as Data, options: [])as! NSDictionary

                    print("json data is--->",jsondata)



            self.get_dest = jsondata.object(forKey: "destination_addresses")as! NSArray



            let get_dest1:String = self.get_dest.object(at: 0) as! String

                    print("destination is--->",get_dest1)

            self.org_add = jsondata.object(forKey: "origin_addresses")as! NSArray



            let get_org:String = self.org_add.object(at: 0)as! String

                    print("original address is--->",get_org)



            self.row_arr = jsondata.object(forKey: "rows")as! NSArray

            let row_dic = self.row_arr.object(at: 0)as! NSDictionary



            self.ele_arr = row_dic.object(forKey: "elements")as! NSArray



            self.ele_dic = self.ele_arr.object(at: 0)as! NSDictionary



            self.dist_dic = self.ele_dic.value(forKey: "distance")as! NSDictionary

            print("distance text is--->",self.dist_dic.object(forKey: "text")as! String)

            print("distance value is--->",self.dist_dic.object(forKey: "value")as! Int)



           // self.ele_dic = self.ele_arr.object(at: 1)as! NSDictionary



            self.dur_dic = self.ele_dic.value(forKey: "duration")as! NSDictionary



            print("duration text--->",self.dur_dic.value(forKey: "text")as! String)

            print("duration value--->",self.dur_dic.value(forKey: "value")as! Int)



                print("status---->",self.ele_dic.object(forKey: "status")as! String)



                }

                catch

                {

                    print("error is--->",error.localizedDescription)

                }

            }

        };task.resume()



    }