如何使用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;
}
}

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

所以添加了类似于这个功能的东西:

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"
}
]
}

最新更新