【问题标题】:How to use this json struct for decoding in swift using JsonDecoder and print the coordinates如何使用此 json 结构使用 JsonDecoder 快速解码并打印坐标
【发布时间】:2020-07-01 19:11:08
【问题描述】:

Ian 构建一个使用儿子数据进行 Web 服务的应用程序我使用 QuickType 网站将儿子数据转换为结构,但现在我不知道如何在解码儿子数据后访问该结构的成员 这是我需要解码和打印坐标值的整个视图控制器文件,以便我可以在地图工具包中访问它

import UIKit
import MapKit
import Foundation
struct Welcome: Codable {
    let locations: [Location]
}

// MARK: - Location
struct Location: Codable {
    let coordinates: Coordinates
    let country, countryCode: String
    let id: Int
    let latest: Latest
    let province: String

    enum CodingKeys: String, CodingKey {
        case coordinates, country
        case countryCode = "country_code"
        case id, latest, province
    }
}

// MARK: - Coordinates
struct Coordinates: Codable {
    let latitude, longitude: String
}

// MARK: - Latest
struct Latest: Codable {
    let confirmed, deaths, recovered: Int
}
class ViewController: UIViewController {

    @IBAction func btn(_ sender: UIButton) {

        loaddata()
    }
    @IBOutlet weak var mapview: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()




    }

    func loaddata()
    {

         let url = URL(string: "https://coronavirus-tracker-api.herokuapp.com/v2/locations")

        var session = URLSession.shared

        var data = session.dataTask(with: url!) { (data, response, error) in
            let decoder = JSONDecoder()
            do
            {
                  var info =  try decoder.decode(Welcome.self, from: data!)

                print(info.locations[0].coordinates.latitude)            }

            catch
            {
                print("\(error)")
            }

        }
    }


}

【问题讨论】:

    标签: ios json swift parsing


    【解决方案1】:

    使用以下代码将 json 对象转换为可编码的结构。希望这可以帮助!

    do {
                let data = "\(yourJson)".data(
                    using: String.Encoding.utf8, allowLossyConversion: false
                )
    
                let dataCodable = try JSONDecoder().decode(Coordinates.self, from: data!)
               print(dataCodable)
            } catch {
                return nil
            }
    

    【讨论】:

    • 什么应该放在“(你的Json)”中
    • 你的 json 对象。您要转换的那个
    • 我尝试了 JSONDecoder,方法是传递 Welcome 结构并访问 location 结构对象数组以打印 url 返回的 json 对象数组的坐标
    • 输出是什么?
    • 我没有得到任何输出我试过 print(info.location[0].coordinates.latitude)
    【解决方案2】:

    现在我发现我没有在共享数据任务之后调用 resume() ,所以添加后它不会执行完美地工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      相关资源
      最近更新 更多