首页 > 解决方案 > 如何使用 Firebase 数据库的结果 JSON 统一制作排行榜

问题描述

我正在使用 unity3d 和 Firebase。可以向数据库发送数据,也可以接收,但是不知道在项目中如何使用。我需要将此 json 文件转换为具有名称和分数的数组,但我无法得到它:(

{
    "Elisa" : {
      "name" : "Elisa",
      "score" : "53"
    },
    "Javi" : {
      "name" : "Javi",
      "score" : "12"
    },
    "Jon" : {
      "name" : "Jon",
      "score" : "33"
    }
}

我使用这个类

[Serializable]
public class Points
{
    public string name;
    public string score;



    public Points(string _name, string _score)
    {
        this.name = _name;
        this.score = _score;
    }
}

如果你想看我的代码,是这样的:

using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
using System;

public class DatabaseManager : MonoBehaviour
{

    DatabaseReference reference;
    // Start is called before the first frame update
    void Start()
    {
        // Set this before calling into the realtime database.
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://project-SecretCode.firebaseio.com/");

        // Get the root reference location of the database.
        reference = FirebaseDatabase.DefaultInstance.RootReference;

    }

    public void ButtonLoad()
    {

        ReadDataBase();
    }
    //leee toda lavase de daton en el apartado score
    [ContextMenu("ReadDataBase")]
    void ReadDataBase()
    {
        //reference
        FirebaseDatabase.DefaultInstance
       .GetReference("Score")
       // .GetReference("Score").Child("javi")

       .GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                //Debug.Log(snapshot.GetRawJsonValue());

                string jsonStr = snapshot.GetRawJsonValue(); //result Json To String
                Debug.Log(jsonStr);
            }
        });


    }
}
[Serializable]
public class Points
{
    public string name;
    public string score;



    public Points(string _name, string _score)
    {
        this.name = _name;
        this.score = _score;
    }
}

标签: jsonfirebaseunity3dfirebase-realtime-databaseleaderboard

解决方案


您可以使用以下命令将 Json 字符串转换为 Unity 对象JsonUtility.FromJson<T>

所以添加类似于这个函数的东西:

public static Points FromJSON(string jsonString)
{
    return JsonUtility.FromJson<Points>(jsonString);
}

  1. 似乎您需要添加一个用于保存数组的类,就像在您的代码中它为一个玩家保存的那样:
class PointsArray {
    Points[] allPlayerPoints;
}
  1. 您的 json 目前是一个带有 key:value 的字典,需要[ ]它才能成为一个数组。(然后您不要重复名称):
{
    [
        {
          "name" : "Elisa",
          "score" : "53"
        },
        {
          "name" : "Javi",
          "score" : "12"
        },
        {
          "name" : "Jon",
          "score" : "33"
        }
    ]
}

推荐阅读