我正在尝试使用swift 4解析json,请告诉我其中有什么问题?

时间:2018-11-08 10:50:46

标签: json parsing struct swift4

我正在尝试使用以下方法解析JSON,但是XCode在声明“ data”的地方给了我一个错误。

我是新来的,我不明白哪里出了问题。请帮助我。

import UIKit

struct Contacts: Decodable {

    let id: Int
    let name: String
    let email: String

}

class ViewController: UIViewController {

    override func viewDidLoad()
    {
        super.viewDidLoad()

        let urlString = "https://api.androidhive.info/contacts/"
        guard let url = URL(string: urlString) else {return}

        URLSession.shared.dataTask(with: url) { (data, response, error) in
        }

        guard let data = data  else {return}
        //let datastring = String(data: data, encoding: .utf8)

        do
        {
            let contact = try JSONDecoder().decode([Contacts].self, from: data)
            print(contact.name)

        } catch let jsonErr {
            print("Error deserializing json:", jsonErr)
        }
    }
}

3 个答案:

答案 0 :(得分:2)

三个主要问题。

  1. 您将忽略根对象,该对象是包含contacts数组的字典。
  2. id的值为String,而不是Int
    硬规则是:双引号中的所有内容都是String甚至"12""false"
  3. 您必须继续执行任务,然后将用于解析JSON 的代码放入完成处理程序中。

struct Root : Decodable {

    let contacts : [Contact]
}

struct Contact : Decodable { // It's recommended to name this kind of struct in singular form

    let id, name, email: String
}

...

override func viewDidLoad()
{
    super.viewDidLoad()

    let urlString = "https://api.androidhive.info/contacts/"
    guard let url = URL(string: urlString) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, error) in
       if let error = error { print(error); return }

       do {
          let result = try JSONDecoder().decode(Root.self, from: data!)
          let contacts = result.contacts
          for contact in contacts {
              print(contact.name)
          }

       } catch {
           print("Error deserializing json:", error)
       }

    }.resume()
}

答案 1 :(得分:0)

//
//  ViewController.swift
//  PostMethodTest
//
//  Created by HABIB UR REHMAN on 12/11/2018.
//  Copyright © 2018 HABIB UR REHMAN. All rights reserved.
//

import UIKit
class ViewController: UIViewController {

  struct Resturant: Decodable {
        var name: String
        var deliveryCharges: String
        var email: String

        init(_ dictionary: [String: Any]) {
            self.name = dictionary["name"] as? String ?? ""
            self.deliveryCharges = dictionary["deliveryCharges"] as? String ?? ""
            self.email = dictionary["email"] as? String ?? ""

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()


        guard let url = URL(string: "your Link Here ") else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"


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

            guard let dataResponse = data,
                error == nil else {
                    print(error?.localizedDescription ?? "Response Error")
                    return }
            do{
                //here dataResponse received from a network request
                let jsonResponse = try JSONSerialization.jsonObject(with:
                    dataResponse, options: [])
                print(jsonResponse) //Response result
            } catch let parsingError {
                print("Error", parsingError)
            }
        }
        task.resume()

        }


}

答案 2 :(得分:-1)

请尝试此操作对我有用。

func getContactListsApiCalling() {

     var request = URLRequest(url: URL(string: "https://api.androidhive.info/contacts/")!)

    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let session = URLSession.shared
    let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in

        do {
            if let Data = data {

                let responseJSON = try JSONSerialization.jsonObject(with: Data) as? Dictionary<String, AnyObject> ?? [:]

                if let contacts = responseJSON["contacts"] as? [[String :AnyObject]] {

                    for contact in contacts {


                        let id  = contact["id"] as? String ?? ""
                        let name  = contact["name"] as? String ?? ""
                        let email   = contact["email"] as? String ?? ""
                        let address  = contact["address"] as? String ?? ""
                        let gender    = contact["gender"] as? String ?? ""

                        print(id,name,email,address,gender)


                    }


                }
            }
        } catch {

            print("error")
        }
    })
    task.resume()
}

}