【问题标题】:SWIFT 4, Xcode 9, JSON DECODERSWIFT 4、Xcode 9、JSON 解码器
【发布时间】:2017-12-22 05:33:09
【问题描述】:

我现在很困。我正在尝试为一年的品牌和型号解析 JSON 返回。它隐藏在一系列字典中,解码器很难将它们拉出来。我做错了什么?

public struct Page: Decodable {
let Count: Int
let Message: String
let SearchCriteria: String
let Results: [car]}


public struct car: Decodable {
let ModelYear: String
let Make: String
let Model: String
let VIN: String}


        let session = URLSession.shared
        let components = NSURLComponents()
        components.scheme  = "https"
        components.host = "vpic.nhtsa.dot.gov"
        components.path = "/api/vehicles/decodevinvaluesextended/\(VIN)"
        components.queryItems = [NSURLQueryItem]() as [URLQueryItem]
        let queryItem1 = NSURLQueryItem(name: "Format", value: "json")
        components.queryItems!.append(queryItem1 as URLQueryItem)
        print(components.url!)

 let task =  session.dataTask(with: components.url!, completionHandler: {(data, response, error) in
          guard let data = data else { return }
            do
                {
                    //let Result = try JSONDecoder().decode(Page.self, from: data)
                   // let PageResult = try JSONDecoder().decode(Page.self, from: data)
                    let json = try JSONDecoder().decode(Page.self, from: data)
                    let Results = json.Results;


                  print(Results)

【问题讨论】:

  • 你得到什么行为,你期望什么行为?
  • 感谢您的提问。这是我得到的,但是我希望能够分别调用这些值中的每一个并将它们合并到一个标签中。 [carloc4.car(ModelYear: "2006", Make: "NISSAN", Model: "Sentra", VIN: "3n1cb51d76l469588")]

标签: json swift4 decoder xcode9-beta


【解决方案1】:

首先强烈建议遵守 Swift 命名约定,变量名以小写字母开头,结构以大写字母开头

public struct Page: Decodable {

    private enum CodingKeys : String, CodingKey {
        case count = "Count", message = "Message", searchCriteria = "SearchCriteria", cars = "Results"
    }

    let count: Int
    let message: String
    let searchCriteria: String
    let cars: [Car]
}


public struct Car: Decodable {

    private enum CodingKeys : String, CodingKey {
        case modelYear = "ModelYear", make = "Make", model = "Model", VIN
    }

    let modelYear: String
    let make: String
    let model: String
    let VIN: String
}

cars 数组位于变量 result 中。此代码打印所有值

let result = try JSONDecoder().decode(Page.self, from: data)
for car in result.cars {
     print("Make: \(car.make), model: \(car.model), year: \(car.modelYear), VIN: \(car.VIN)")
}

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多