这是我的代码.但我不知道该如何设定价值.它必须手动完成,因为实际结构比这个例子稍微复杂一些.
有什么帮助吗?
struct Something: Decodable {
value: [Int]
enum CodingKeys: String, CodingKeys {
case value
}
init (from decoder :Decoder) {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = ??? // < --- what do i put here?
}
}
Run Code Online (Sandbox Code Playgroud)
vad*_*ian 26
由于一些错误/错别字,您的代码无法编译.
解码Int写入数组
struct Something: Decodable {
var value: [Int]
enum CodingKeys: String, CodingKey {
case value
}
init (from decoder :Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = try container.decode([Int].self, forKey: .value)
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果问题中的示例代码代表整个结构,则可以将其缩减为
struct Something: Decodable {
let value: [Int]
}
Run Code Online (Sandbox Code Playgroud)
因为初始化器和CodingKeys可以推断出来.
感谢Joshua Nozzi的提示。这是我实现解码Int数组的方法:
let decoder = JSONDecoder()
let intArray = try? decoder.decode([Int].self, from: data)
Run Code Online (Sandbox Code Playgroud)
无需手动解码。
就我而言,这个答案非常有帮助
我有一个JSON格式:"[ "5243.1659 EOS" ]"
因此,您可以在没有密钥的情况下解码数据
struct Model: Decodable {
let values: [Int]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let values = try container.decode([Int].self)
self.values = values
}
}
Run Code Online (Sandbox Code Playgroud)
let decoder = JSONDecoder()
let result = try decoder.decode(Model.self, from: data)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10063 次 |
| 最近记录: |