json - Swift - 解码数组 JSON 数据的数组

标签 json swift jsondecoder

我正在使用 Swift 5,我正在尝试创建一个结构来保存 Google 表格 API 调用的内容。 我坚持使用“值”键,我想获取哪些值,更改为 Int 类型并存储在我最近可以使用的单独数组变量中。

这是 API 的一个结果:

{
 "range": "Sheet1!A2:B4",
 "majorDimension": "ROWS",
 "values": [
   [
     "-10",
     "12"
   ],
   [
     "-9",
     "-15"
   ],
   [
     "-8",
     "-9"
   ]
   [
     "-7",
     "4"
   ]
 ]
}

在我以前的方法中,我得到了一个错误:“预期解码字符串但发现了一个数组。”

所以我的问题是“值”的内部结构应该如何完成任务?

struct Sheet: Decodable {
    let range: String?
    let majorDimension: String?
    let values: [Values]?  
}

do {
   let json = try JSONDecoder().decode(Sheet.self, from: data)

  } catch let error {
      print(error as Any)
  }

谢谢!

最佳答案

请注意,您的 JSON 在此数组后缺少一个逗号:

[
 "-8",
 "-9"
]

假设您修复了该问题,您需要创建 values [[String]]? 的类型:

struct Response: Codable {
    // you don't actually need optional properties if you are sure they exist
    let range: String?
    let majorDimension: String?
    let values: [[String]]?

    // you don't need CodingKeys here since all your property names match the JSON keys
}

如果您希望数字为 Double,您可以这样做(假设数字始终有效):

struct Response: Codable {
    let range: String?
    let majorDimension: String?
    let values: [[Double]]?

    // now you need CodingKeys, but you don't need to give them raw values
    enum CodingKeys: String, CodingKey {
        case range
        case majorDimension
        case values
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        range = try container.decodeIfPresent(String.self, forKey: .range)
        majorDimension = try container.decodeIfPresent(String.self, forKey: .majorDimension)
        // use map to transform the strings to doubles
        values = try container.decodeIfPresent([[String]].self, forKey: .values)?
            .map { $0.map { Double($0)! } }
            // or if you want to filter out the invalid numbers...
            // .map { $0.compactMap(Double.init) }
    }
}

关于json - Swift - 解码数组 JSON 数据的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697119/

相关文章:

python - 从远程数据库获取并存储到本地 Django

java - 判断ByteArrayOutputStream的类型是JSONArray还是JSONObject?

swift - 创建功能以设置导航 Controller

ios - 使用 JSONDecoder 解码带有空对象的 JSON

Python 请求返回 JSON 解码器错误

html - 如何组合多个 JSON-LD 标记?

javascript - 自动完成 json 数据

ios - 在 Swift MVC 中保存 TableView 数据

swift - 为什么总值不随每个 switch case 更新? swift 4

json - Swift:如何使用来自 SocketIO emitWithAck 方法的响应