编码JSON,Swift 4.1的关键难点

时间:2018-04-05 14:35:55

标签: json swift codable

我有一个带有响应主体的JSON,如下所示:

{
    "Count": 116,
    "Message": "Result returned successfully",
    "SearchCriteria": "Search Criteria",
    "Results": [
        {
            "Value": "",
            "ValueId": "",
            "Variable": "Suggested VIN",
            "VariableId": 142
        },
        < 115 more like this >
    ]
}

初始尝试

我最初尝试创建编码密钥,如下所示:

struct ResponseBody: Codable {
    var count: Int
    var message: String
    var searchCriteria: String
    var results: [Result]

    enum ResponseKeys: String, CodingKey {
        case count = "Count"
        case message = "Message"
        case searchCriteria = "SearchCriteria"
        case results = "Results"
    }
}

struct Result: Codable {
    var value: String?
    var valueId: String?
    var variable: String
    var variableId: Int

    enum ResultKeys: String, CodingKey {
        case value = "Value"
        case valueID = "ValueId"
        case variable = "Variable"
        case variableID = "VariableId"
    }
}

没有来自编译器的抱怨,我试图用这段代码解码它:

// network request code
    let decoder = JSONDecoder()
    var responseData: ResponseBody?

    do {
      responseData = try decoder.decode(ResponseBody.self, from: data)
      guard let responseData = responseData else { return }
      let vehicle = self.createVehicleStruct(from: responseData)
      self.dispatchGroup.notify(queue: .main, execute: {
        completion(vehicle)
      })
    } catch {
      print(error, error.localizedDescription)
    }

产生了这个error

  

keyNotFound(CodingKeys(stringValue:&#34; count&#34;,intValue:nil),   Swift.DecodingError.Context(codingPath:[],debugDescription:&#34; No   与键CodingKeys相关联的值(stringValue:\&#34; count \&#34;,intValue:   nil)(\&#34; count \&#34;)。&#34;,underlyingError:nil))无法读取数据   因为它不见了。

工作,但可怕的尝试

渴望&#34;继续前进&#34;,我尝试了以下内容并且我能够解析JSON,但是不符合Swift命名约定会让我感到沮丧:

struct ResponseBody: Codable {
    var Count: Int
    var Message: String
    var SearchCriteria: String
    var Results: [Result]
}

struct Result: Codable {
    var Value: String?
    var ValueId: String?
    var Variable: String
    var VariableId: Int
}

现在,我现在回到试图在structs中找到漂亮,干净的名字,因为我知道网络部分有效。经过进一步调查,我需要提供一个init(from decoder:),所以我重构如下:

struct ResponseBody: Decodable {
    var count: Int
    var message: String
    var searchCriteria: String
    var results: [Result]

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

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let count: Int = try container.decode(Int.self, forKey: .count)
        let message: String = try container.decode(String.self, forKey: .message)
        let searchCriteria: String = try container.decode(String.self, forKey: .searchCriteria)
        let results: [Result] = try container.decode([Result].self, forKey: .results)

        // FIXME: Extra argument 'message' in call
        self.init(count: count, message: message, searchCriteria: searchCriteria, results: [results])
    }
}

struct Result: Decodable {
    var value: String?
    var valueID: String?
    var variable: String
    var variableID: Int

    private enum CodingKeys: String, CodingKey {
        case value = "Value"
        case valueID = "ValueId"
        case variable = "Variable"
        case variableID = "VariableId"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let value: String = try container.decode(String.self, forKey: .value)
        let valueID: String = try container.decode(String.self, forKey: .valueID)
        let variable: String = try container.decode(String.self, forKey: .variable)
        let variableID: Int = try container.decode(Int.self, forKey: .variableID)

        // FIXME: Extra argument 'valueID' in call
        self.init(value: value?, valueID: valueID?, variable: variable, variableID: variableID)
    }
}

我在调用init时在init(from decoder:)中收到错误:

Extra argument 'valueID' in call

我无法弄清楚我的错误在哪里。如果您有任何建议,我欢迎您的意见。谢谢你的阅读。

1 个答案:

答案 0 :(得分:8)

你的枚举必须被称为CodingKeys,它们的案例名称必须与struct属性的名称相匹配(例如variableIDvariableId不一样,但它们必须是)。

一旦你解决了这个问题,一切都会好起来的。

因此,我能够使用这两个结构解析您提供的JSON,没问题:

struct ResponseBody: Codable {
    var count: Int
    var message: String
    var searchCriteria: String
    var results: [Result]

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

struct Result: Codable {
    var value: String?
    var valueId: String?
    var variable: String
    var variableId: Int

    enum CodingKeys: String, CodingKey {
        case value = "Value"
        case valueId = "ValueId"
        case variable = "Variable"
        case variableId = "VariableId"
    }
}