【问题标题】:Deserializing JSON Response from unity's Firebask SDK Error反序列化来自统一的 Firebask SDK 错误的 JSON 响应
【发布时间】:2021-01-23 09:57:59
【问题描述】:

目前我正在使用统一发布保存在 firebase RTDB 中的 cmets。

这里是发帖代码:

Comment NewComment = new Comment("User1", "Great App!");
Dictionary<string, System.Object> childUpdates = new 
Dictionary<string, System.Object>();
childUpdates["NewUpdate2"] = NewComment.ToDict();
_database.GetReference("DumbData").UpdateChildrenAsync(childUpdates);

运行良好并将数据发布到 Firebase

这里的参考是评论类。

[System.Serializable]
public class Comment
{
    public Comment(string Name,string Content)
    {
        this.Name = Name;
        this.Content = Content;
    }
    public Dictionary<string,System.Object> ToDict()
    {
        Dictionary<string, System.Object> result = new Dictionary<string, System.Object>();
        result["Name"] = this.Name;
        result["Content"] = this.Content;
        return result;
    }
    public string Name;
    public string Content;
}

Firebase 会正确注册接收到的数据。

但是当收到数据时,我会这样做

var dataSnapShot = await _database.GetReference("DumbData").GetValueAsync();
var Results  = dataSnapShot.GetRawJsonValue();
var temp= JsonUtility.FromJson<Dictionary<string, Comment>>(Results)

但问题是 FromJSON 函数到处都返回 Null,尽管接收到的 JSON 与 Firebase 上的结构正确匹配,但作为参考,上面的 Results 变量如下所示:

{"NewUpdate":{"Content":"Great App!","Name":"User1"},"NewUpdate2":{"Content":"Great App!","Name":"User2"}}

这就是我被卡住的地方,我无法将响应反序列化以能够使用它。

【问题讨论】:

标签: c# firebase unity3d firebase-realtime-database


【解决方案1】:

JsonUtility 对于嵌套对象、字典等非常有限。

我建议你使用另一个库来处理 JSON 序列化和反序列化,例如,你可以使用 Newtonsoft 库,或者使用我自己的 JsonManager(repo 包括它的工作原理和使用方法的示例它)。

Newtonsoft:

序列化:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

反序列化:

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

因此,在反序列化不起作用的特定情况下,您应该执行以下操作:

Dictionary<string, Comment> temp = JsonConvert.DeserializeObject<Dictionary<string, Comment>>(json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多