【问题标题】:How can I print out the content of a Dictionary<string, object>?如何打印 Dictionary<string, object> 的内容?
【发布时间】:2022-01-22 02:39:28
【问题描述】:

Firebase 数据库在应用中的其他类似操作之间需要时无法下载数据。

System.Collections.Generic.Dictionary`2[System.String,System.Object]

Firebase 有时在应用程序的类似操作中间无法执行新的GetValueASync 并抛出System.Collections.Generic.Dictionary2[System.String,System.Object]` 作为快照值。

重现步骤: 使用实时数据库设置任何统一项目,多次不间断地执行: .GetValueAsync().ContinueWithOnMainThread(task =&gt; 那么您将获得 System.Collections.Generic.Dictionary2[System.String,System.Object]` 的值,而不是任何子/键/数据库值。

public void aaaa() {
    Reference.Child("Users").OrderByChild("About/XP").StartAt(1).LimitToFirst(12).GetValueAsync().ContinueWithOnMainThread(task => {
      if (task.IsFaulted) {

        return;
      } else if (task.IsCompleted) {
        DataSnapshot Snapshot = task.Result;
        if (Snapshot != null)
          Debug.Log(Snapshot.Value);
        return;
      }
      return;

    });

【问题讨论】:

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


    【解决方案1】:

    “问题”

    如果你在字典上使用ToString (这是Debug.Log 在内部执行的操作),或者通常任何没有显式实现它的类型的对象,就会发生这种情况,它只会返回与GetType().FullName 相同的内容.

    Object.ToString 方法的默认实现返回对象类型的完全限定名称。

    所以看起来类型是Dictionary&lt;string, object&gt;


    解决方案 1 - 简单循环

    如果你想查看所有你想做的第一级项目,例如

    foreach(var kvp in Snapshot.Value)
    {
        Debug.Log($"Key: {kvp.Key}, Value: {kvp.Value}");
    }
    

    请注意:虽然键是string,但值可能又是一个类型(afaik,例如Dictionary&lt;string, object&gt;),没有实现ToString,在这种情况下,它将再次简单地打印出类型名称。


    解决方案 2 - Newtonsoft JSON

    如果您真的想打印出整个结构(只要值是可序列化的),您可以使用 Newtonsoft JSON.Net 并将整个字典转换为人类可读的 JSON 格式。

    Serialize a Dictionary

    string json = JsonConvert.SerializeObject(Snapshot.Value, Formatting.Indented);
    Debug.Log(json);
    

    解决方案 3 - Firebase 特定

    我发现在您的特定情况下并不真正需要 Newtonsoft! (我将把它留在这里作为打印字典的一般技巧)

    只需使用GetRawJsonValue

    Debug.Log(Snapshot.GetRawJsonValue());
    

    【讨论】:

    • 相同的代码可以正常工作,并在不运行任何其他 getvalueasync 时向我显示排序用户列表。
    • @gputhread 这样吗?显然,它返回一个确实以有意义的方式实现 ToString 的类型......
    • 它应该返回“firebase 忙,稍后再试”或“位置/url 未到达”,因为它在应用程序空闲时可以正常工作。
    • @gputhread 再次:您在控制台中打印的 IS 结果。它是一个Dictionary&lt;string, object&gt;,您现在可以使用它来通过键进一步访问返回值...它会打印System.Collections.Generic.Dictionary2[System.String,System.Object]`,因为这正是您尝试得到的结果使用Debug.Log(new Dictionary&lt;string, object&gt;().ToString()); .. 它只是意味着这种类型没有有意义的ToString 实现,但是你得到了一个有效的结果
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 2014-10-22
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多