如何使用swift 4解析JSON

时间:2018-05-16 20:49:21

标签: json swift codable decodable

我很难弄清楚水果的细节

{
  "fruits": [
    {
      "id": "1",
      "image": "https://cdn1.medicalnewstoday.com/content/images/headlines/271/271157/bananas.jpg",
      "name": "Banana"
    },
    {
      "id": "2",
      "image": "http://soappotions.com/wp-content/uploads/2017/10/orange.jpg",
      "title": "Orange"
    }
  ]
}

想要使用" Decodable"

解析JSON
struct Fruits: Decodable {
    let Fruits: [fruit]
}
struct fruit: Decodable {
    let id: Int?
    let image: String?
    let name: String?
}

let url = URL(string: "https://www.JSONData.com/fruits")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in

            guard let data = data else { return }

            do{
                let fruits = try JSONDecoder().decode(Fruits.self, from: data)
                print(Fruits)

            }catch {
                print("Parse Error")
            }

你也可以建议我用cocoapod库来快速下载图像

3 个答案:

答案 0 :(得分:1)

您遇到的问题是因为您的JSON正在为您的水果返回不同的数据。

对于第一个ID,它返回一个名为String的{​​{1}},但在第二个ID中返回一个名为name的字符串。

此外,在解析JSON时,ID似乎是title而不是String

因此,您的数据中有两个可选值。

因此,您的可解码结构应如下所示:

Int

由于您的URL似乎无效,我在主包中创建了JSON文件,并且能够正确解析它:

struct Response: Decodable {
    let fruits: [Fruits]

}

struct Fruits: Decodable {
    let id: String
    let image: String
    let name: String?
    let title: String?
}

希望它有所帮助...

答案 1 :(得分:0)

// Parse Json using decodable
// First in create Structure depends on json 
//
//
//

struct Countory : Decodable {
    let name: String
    let capital: String
    let region: String
}

 let url = "https://restcountries.eu/rest/v2/all"
 let urlObj = URL(string: url)!
 URLSession.shared.dataTask(with: urlObj) {(data, responds, Error) in

   do {
   var countories = try JSONDecoder().decode([Countory].self, from: data!)
    for country in countories {

       print("Country",country.name)
       print("###################")
       print("Capital",country.capital)

        }
        } catch {
         print(" not ")
        }
     }.resume()

答案 2 :(得分:-1)

        Model sample:
        public struct JsonData: Codable{
            let data: [Data]?
            let meta: MetaValue?
            let linksData: LinksValue?

            private enum CodingKeys: String, CodingKey{
                case data
                case meta
                case linksData = "links"
            }
        }


     enum BackendError: Error {
    case urlError(reason: String)
    case objectSerialization(reason: String)
}

struct APIServiceRequest {

    static func serviceRequest<T>(reqURLString: String,
                                  resultStruct: T.Type,
                                  completionHandler:@escaping ((Any?, Error?) -> ())) where T : Decodable {
        guard let url = URL(string: reqURLString) else {
            print("Error: cannot create URL")
            let error = BackendError.urlError(reason: "Could not construct URL")
            completionHandler(nil, error)
            return
        }
        let urlRequest = URLRequest(url: url)

        let session = URLSession.shared

        let task = session.dataTask(with: urlRequest) { (data, response, error) in
            guard error == nil else {
                completionHandler(nil, error)
                return
            }

            guard let responseData = data else {
                print("Error: did not receive data")
                let error = BackendError.objectSerialization(reason: "No data in response")
                completionHandler(nil, error)
                return
            }

            let decoder = JSONDecoder()
            do {
                let books = try decoder.decode(resultStruct, from: responseData)
                completionHandler(books, nil)
            } catch {
                print("error trying to convert data to JSON")
                print(error)
                completionHandler(nil, error)
            }
        }

        task.resume()
    }

}

POST方法

func loginWS(endpoint: String, completionHandler: @escaping (Any?) -> Swift.Void) {

    guard let sourceUrl = URL(string: endpoint) else { return }
    let request = NSMutableURLRequest(url: sourceUrl)

    let session = URLSession.shared
    request.httpMethod = "POST"
    request.addValue(vehiceHeader, forHTTPHeaderField: "X-Vehicle-Type")
    request.addValue(contentHeader, forHTTPHeaderField: "Content-Type")

    let task = session.dataTask(with: request as URLRequest) { data, response, error in

        guard let data = data else { return }
        do {
            let responseData = try JSONDecoder().decode(JsonData.self, from: data)
            print("response data:", responseData)
            completionHandler(responseData)
        } catch let err {
            print("Err", err)
        }
        }.resume()
}