简体   繁体   English

如何在 Swift 中使用 Codable 解析 JSON?

[英]How to parse JSON using Codable in Swift?

I am able to parse JSON using JSONSerialization , but unable to parse with Codable .我能够使用JSON JSONSerialization,但无法与可编码解析解析。

the json look like this: json 看起来像这样:

[
{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
  }

Please help me with the code.请帮我写代码。

able to parse using JSONSerialization : data coming能够使用 JSONSerialization 解析:数据即将到来

Unable to parse JSON with Codable: data not coming无法使用 Codable 解析 JSON:数据未到来

struct jsonDataModel: Codable{

var name: String
var userName: String
var email: String

init(name: String, username: String, email: String){
    self.name = name
    self.userName = username
    self.email = email
}
}
class WebviewViewController: UIViewController, WKNavigationDelegate {

@IBOutlet weak var testWebView: WKWebView!


//var itemsArray = [jsonDataModel]()


override func viewDidLoad() {
    super.viewDidLoad()
    serviceCall()
    }

   func serviceCall()
    {

        let jsonString = "https://jsonplaceholder.typicode.com/users"

        let jsonData = jsonString.data(using: .utf8)!

            do {
               let jsonDecoder = JSONDecoder()
               let user = try jsonDecoder.decode(jsonDataModel.self, from: jsonData)
                print("all data \(user)")
                print("Hello \(user.name), \(user.userName), \(user.email) ")
            } catch {
                print("Unexpected error: \(error).")
            }
    }
    }

Please help me to parse json with codable.请帮我解析带有可编码的json。

Try this example.试试这个例子。

import UIKit
import Foundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            do{
                let jsonDataModels = try JSONDecoder().decode([JSONDataModel].self, from: data)
                print(String(data: data, encoding: .utf8)!)
                print("jsonDataModels: \(jsonDataModels)")
            }catch{}
        }
        task.resume()

    }
}


struct JSONDataModel: Codable {
    let id: Int
    let name, username, email: String
    let address: Address
    let phone, website: String
    let company: Company
}


struct Address: Codable {
    let street, suite, city, zipcode: String
    let geo: Geo
}


struct Geo: Codable {
    let lat, lng: String
}


struct Company: Codable {
    let name, catchPhrase, bs: String
}

First of all, if you're using a URL , then to get data you need to use a networking api .首先,如果您使用的是URL ,那么要获取data您需要使用网络 api URLSession is the iOS provided api to perform network operations like download/upload. URLSessioniOS提供的 api,用于执行下载/上传等网络操作。

So, just using Codable doesn't make any sense.所以,仅仅使用Codable没有任何意义。 You need to first have the data in order to parse it with Codable .您需要首先拥有data才能使用Codable解析它。

Here is the model,这是模型,

struct Model: Codable {
    let id: Int
    let name, username, email: String
}

And you can use it in your controller's viewDidLoad() method,你可以在controller's viewDidLoad()方法中使用它,

if let url = URL(string: "https://jsonplaceholder.typicode.com/users") {
    URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
        if let data = data {
            do {
                let response = try JSONDecoder().decode([Model].self, from: data)
                print(response.map({ $0.name })) //prints all the names
            } catch {
                print(error)
            }
        }
    }.resume()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM