我有一个示例 JSON,其中它只是一个字符串数组并且没有键,我想使用 Decodable
协议(protocol)来使用 JSON 并从中创建一个简单的模型。
json 看起来像这样:
{ "names": [ "Bob", "Alice", "Sarah"] }
只是一个简单数组中的字符串集合。
我不确定的是如何使用新的 Swift Decodable
协议(protocol)在没有 key 的情况下将其读入模型。
我见过的大多数例子都假设 JSON 有一个键。
即:
// code from: Medium article: https://medium.com/@nimjea/json-parsing-in-swift-2498099b78f
struct User: Codable{
var userId: Int
var id: Int
var title: String
var completed: Bool
}
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
let model = try decoder.decode([User].self, from:
dataResponse) //Decode JSON Response Data
print(model)
} catch let parsingError {
print("Error", parsingError)
}
上面的例子假设 json 是一个键值;如何使用 decodable 协议(protocol)在没有 key 的情况下对 JSON 进行解码?
谢谢
最佳答案
这个JSON对应的struct是
struct User: Decodable {
let names: [String]
}
解码
let model = try decoder.decode(User.self, from: dataResponse)
并用
获取名字let names = model.names
或者传统上没有 JSONDecoder
的开销
let model = try JSONSerialization.jsonObject(with: dataResponse) as? [String:[String]]
关于json - Swift - 使用 Decodable 解码仅包含字符串的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959301/