我正在解析需要从服务器上的字典(这是一种遗留数据格式)转换为客户端上的简单字符串数组的响应。因此,我想将名为“data”的键解码为字典,这样我就可以遍历键并在客户端创建一个字符串数组。
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
do {
let some_data_dictionary = try values.decode([String:Any].self, forKey: CodingKeys.data)
for (kind, values) in some_data_dictionary {
self.data_array.append(kind)
}
} catch {
print("we could not get 'data' as [String:Any] in legacy data \(error.localizedDescription)")
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是: Ambiguous reference to member 'decode(_:forKey:)'
我想通过解析 firestore 数据库的响应来解码时间戳(由 FirebaseFirestore.Timestamp 在 swift 中定义)。
编译器告诉我从服务器解析以下代码:
实例方法“decode(_:forKey:)”要求“Timestamp”符合“Decodable”
created = try container.decode(FirebaseFirestore.Timestamp.self, forKey: .created)
Run Code Online (Sandbox Code Playgroud)
我也无法使用以下行进行编码(在本地保存或发送到服务器):
try container.encode(created, forKey: .created)
Run Code Online (Sandbox Code Playgroud)
编译器说:
无法将“Timestamp”类型的值转换为预期的参数类型“String”
完整的复制粘贴如下
另外,时间戳似乎是字典,而不是整数,因为当我尝试将时间戳解码为整数时,出现错误:
Expected to decode Int but found a dictionary instead.
Run Code Online (Sandbox Code Playgroud)
但我们都知道 [String:Any] (即字典)无法解码。
import FirebaseFirestore
class SomeClassToParseFromFirestoresDatabase: Codable
{
var created = FirebaseFirestore.Timestamp.init(date: Date())
private enum CodingKeys: String, CodingKey
{
case created
}
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: CodingKeys.self)
do
{
try container.encode(created, forKey: .created)
}
catch let error
{
print("error encoding …Run Code Online (Sandbox Code Playgroud) 是否可以查询firebase以获取集合中文档的字段,其中特定字段的数组中的元素数大于0
在我的示例中,每个文档都有一个名为“ people”的字段,其中包含一个整数数组(或者该数组为空)。
我的搜索总是返回0个文档,但是当我在firestore数据库管理面板中搜索时,可以看到一些文档。
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
admin.initializeApp();
var db = admin.firestore();
export const helloWorld = functions.https.onRequest(function(req,res)
{
var all_users = db.collection('users');
var query = all_users.where("people.length", ">", 0).get().then(snapshot =>
{
let docs = snapshot.docs;
//return 1st document found
res.send(docs[0].data());
});
query.catch(error =>
{
res.status(500).send(error);
});
});
Run Code Online (Sandbox Code Playgroud)