【发布时间】:2020-06-06 14:23:01
【问题描述】:
目前我从位于 http 服务器上的 json 文件获取数据
if let url = NSURL(string: "https://test.com/test") {
do {
let data = try Data(contentsOf: url as URL)
let decoder = JSONDecoder()
jsonData = try decoder.decode(TestList.self, from: data)
} catch {
print("error:\(error)")
}
struct TestList: Decodable {
enum CodingKeys: String, CodingKey {
case items
}
let items: [Item]
}
struct Item: Decodable {
var item_type: String?
//...
enum CodingKeys: String, CodingKey {
case item_type
//...
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.item_type = try? container.decode(String.self, forKey: .mtype)
//...
}
}
一切正常,但当 我切换到 firebase 实时数据库并获得相同的 json 数据
Database.database().reference().child("items").observeSingleEvent(of: .value, with: { snapshot in
guard let value = snapshot.value else { return }
do {
self.jsonData = try FirebaseDecoder().decode(TestList.self, from: value)
} catch let error {
print(error)
}
})
我的 JSON:
{
"items": [
{
"item_type": "Rap",
"1": "Kastro",
"2": "EDI",
"3": "Noble",
"4": ""
},
{
"item_type": "Rock",
"1": "Nickelback",
"2": "",
"3": "",
"4": ""
},
{
"item_type": "Pop",
"1": "Ringo",
"2": "",
"3": "",
"4": ""
}
]
}
收到此消息:
typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "不是 字典”,基础错误:无))
如何解决这个错误?
【问题讨论】:
-
Firebase 实时数据库不能直接使用 JSON,但是有一个很棒的库可以帮助您:github.com/alickbass/CodableFirebase
-
我试过了,但它不能与 Decodable 一起工作
-
你能显示你得到的 Json 响应吗?因为你得到的响应是一个字典,而这里的 testlist 是一个数组。
-
是的,但为什么当 json 文件位于 http 服务器上时它可以工作?
标签: json swift firebase-realtime-database