如何将对象存储为字符串? [英] How to store object as string?
问题描述
我以前从未使用过Firebase,并且正在尝试将实时数据库连接到我的Unity应用程序.现在,我的应用程序从Json文件中提取数据并将其存储为字符串.为了避免破坏程序的其余部分(我是编程新手,没有技能来重写,但是正在学习),我想将Firebase快照转换为字符串并以当前Json的方式读取它文件是.那可能吗?快照是一个目标文件,我需要从中获取字符串数据.
I've never used Firebase before, and am trying to connect a real-time database to my Unity app. Right now my app pulls data from a Json file and stores it as a string. To avoid breaking the rest of my program (I'm very new to programming and don't have the skills to rewrite it, but am learning), I want to convert the Firebase snapshot into a string and read it the way my current Json file is. Is that possible? The snapshot is an object file, and I need to get the string data from it.
这是捕获快照的代码.
DataSnapshot snapshot = task.Result;
我也声明了这个字符串.
I also have this string declared.
private string gameDataFileName = "data.json";
然后这是从文件加载数据的功能.
Then this is the function to load the data from the file.
private void LoadGameData()
{
string filePath = Path.Combine(Application.streamingAssetsPath,
gameDataFileName);
if (File.Exists(filePath))
{
string dataAsJson = File.ReadAllText(filePath);
GameData loadedData = JsonUtility.FromJson<GameData>(dataAsJson);
allRoundData = loadedData.allRoundData;
}
else
{
Debug.LogError("Cannot load game data!");
}
}
是否有将快照转换为Json或字符串的方法,以便可以将其插入dataAsJson?还是如果没有人能告诉我这样做的正确方法?该应用程序是一款琐事游戏,可在启动该应用程序时下载问题和答案.我不需要刷新数据,我只想能够在不强迫用户下载更新的情况下更新问题,因此我选择使用Firebase.
Is there anyway to convert the snapshot into a Json or string so I can plug it into dataAsJson? Or if not can anyone tell me the proper way to do this? The app is a trivia game that downloads the questions and answers when starting the app. I don't need the data to refresh, I just want to be able to update the questions without forcing the user to download an update, hence my reason for using Firebase.
我应该以其他方式执行此操作吗?我已经搜索了互联网的每个角落,并且阅读的所有内容要么超出我的理解范围,要么在我的情况下不起作用.
Is there a different way I should be doing this? I've searched every corner of the internet and everything I read is either beyond my comprehension or doesn't work in my situation.
推荐答案
To get the raw JSON of a DataSnapshot
call its GetRawJsonValue()
method. You should then be able to pass that into your JsonUtility.FromJson
method.
这篇关于如何将对象存储为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!