我有以下序列化的类:
[System.Serializable]
public class Question
{
public string question;
public List<string> answers;
public string correct;
public Question(string question, List<string> answers, string correct){
this.question = question;
this.answers = answers;
this.correct = correct;
}
}
以及以下questions
数组:
questions = new List<GameManager.Question>();
questions.Add(new GameManager.Question("2+2?", new List<string> { "4", "5", "6" }, "4"));
questions.Add(new GameManager.Question("2*2?", new List<string> { "1", "4", "8" }, "4"));
questions.Add(new GameManager.Question("2/2?", new List<string> { "0", "1", "2" }, "1"));
我需要以json
格式存储此信息,并将其加载以启动问题游戏。
如何使用json加载一系列问题?
答案 0 :(得分:1)
您可以使用newtonsoft.json对对象进行序列化和反序列化。使用非常简单。我认为您必须安装nuget软件包。
此处是有关如何在unity 3d中序列化和保存数据的帖子:Post
答案 1 :(得分:1)
这是一个可行的例子
void Main()
{
var questions = new List<Question>();
questions.Add(new Question("2+2?", new List<string> { "4", "5", "6" }, "4"));
questions.Add(new Question("2*2?", new List<string> { "1", "4", "8" }, "4"));
questions.Add(new Question("2/2?", new List<string> { "0", "1", "2" }, "1"));
var json = JsonConvert.SerializeObject(questions, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
// Define other methods and classes here
public class Question
{
public string question;
public List<string> answers;
public string correct;
public Question(string question, List<string> answers, string correct)
{
this.question = question;
this.answers = answers;
this.correct = correct;
}
}
输出
[
{
"question": "2+2?",
"answers": [
"4",
"5",
"6"
],
"correct": "4"
},
{
"question": "2*2?",
"answers": [
"1",
"4",
"8"
],
"correct": "4"
},
{
"question": "2/2?",
"answers": [
"0",
"1",
"2"
],
"correct": "1"
}
]
您可以通过
将其反序列化为一系列问题var deserialized = JsonConvert.DeserializeObject<Question[]>(json);
答案 2 :(得分:0)
如果已安装NewtonSoft.Json.JsonConvert.SerializeObject
,则可以使用Newtonsoft.Json.JsonConvert.DeserializeObject<T>
和nuget package
。然后只需用JsonProperty
标签,文档(https://www.newtonsoft.com/json/help/html/SerializingJSON.htm)装饰您的媒体资源