json - 如何使用 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;
}
}
解决方案
您可以使用以下命令将 Json 字符串转换为 Unity 对象JsonUtility.FromJson<T>
:
所以添加类似于这个函数的东西:
public static Points FromJSON(string jsonString)
{
return JsonUtility.FromJson<Points>(jsonString);
}
- 似乎您需要添加一个用于保存数组的类,就像在您的代码中它为一个玩家保存的那样:
class PointsArray {
Points[] allPlayerPoints;
}
- 您的 json 目前是一个带有 key:value 的字典,需要
[
]
它才能成为一个数组。(然后您不要重复名称):
{
[
{
"name" : "Elisa",
"score" : "53"
},
{
"name" : "Javi",
"score" : "12"
},
{
"name" : "Jon",
"score" : "33"
}
]
}
推荐阅读
- gallery - 如何在方形空间 7.1 中使画廊幻灯片的下一个/上一个箭头更大
- python - 在 Python 中拟合多项式回归?
- python - 使用两个嵌套的 for 循环打印两个列表的公共元素
- reactjs - React.memo 重新渲染递归组件而不运行 areEqual 函数
- python - Python3.9 多处理导致 MacOS 上的范围错误
- config - 如何使用自己的快捷键在 tmux 中的窗口之间切换?
- python - 如何在 python 的一行中放置特定数量的整数?
- css - WordPress-CSS:在视频播放器上设置相等的高度
- flutter - 使用 FloatingButton (Flutter) 随机输出文本
- swift - 如何在 SwiftUI 中调整背景图像的大小而不影响屏幕视图?