【问题标题】:RawJsonValues in Unity & FirebaseUnity 和 Firebase 中的原始 Json 值
【发布时间】:2021-01-15 11:29:40
【问题描述】:

SetRawJsonValueAsync 的一些问题。当我使用文档中的代码时:

    public class User
{
    public string username;
    public string email;

    public User()
    {
    }

    public User(string username, string email)
    {
        this.username = username;
        this.email = email;
    }
}

private void writeNewUser(string userId, string name, string email)
{
    User user = new User(name, email);
    string json = JsonUtility.ToJson(user);

    mDatabaseRef.Child("users").Child(userId).SetRawJsonValueAsync(json);
}

然后 firebase 会自动将其转换为值树。好的。但是当我试图让他们回来时:

    public void get_data()
{
    mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
        if (task.IsCompleted)
        {
            Debug.Log("completed");
            string json = task.Result.Value;
            User user = JsonUtility.FromJson<User>(json);
            Debug.Log(user.username);
        }
    });
}

它停止并且不打印用户名。为什么?或者我需要如何获取 json raws?

【问题讨论】:

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


    【解决方案1】:

    这里的问题是task.Result.Value 是对数据库中值的 C# 解释。鉴于您发布的代码,我认为应该是IDictionary&lt;string, object&gt;

    你要的是task.Result.GetRawJsonValue():

    public void get_data()
    {
        mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
            if (task.IsCompleted)
            {
                Debug.Log("completed");
                string json = task.Result.GetRawJsonValue();
                User user = JsonUtility.FromJson<User>(json);
                Debug.Log(user.username);
            }
        });
    }
    

    【讨论】:

    • 非常感谢!我可以通过这种方式序列化MonoBehavior脚本吗(我的意思是使用Json),因为添加: MonoBehaviour会导致一些问题。
    • 如果你想填写一个 MonoBehaviour,你需要自己初始化它(使用GameObject.InstantiateGameObject.GetComponent,或GameObject.AddComponent),因为构造函数对于 MonoBehaviour 是无效的在统一。然后你可以使用JsonUtility.FromJsonOverwrite。请注意,您总是会想念Awake,有时会想念Start,因此很难安全地做到这一点?docs.unity3d.com/ScriptReference/…
    • 干杯!很有帮助?
    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多