[英]How to serialize object with list of objects containg list of objects to JSON file?
I am writing simple quiz generator witch will generate quizzes in json format.我正在编写简单的测验生成器女巫将生成 json 格式的测验。 I have 3 classes as an extra lib to menage all quiz.
我有 3 个课程作为管理所有测验的额外库。 Those are: Quiz.cs, Question.cs and Answer.cs.
它们是:Quiz.cs、Question.cs 和 Answer.cs。 I try to serialize Quiz object witch contains list of Questions, witch have 3 fields: question, score and list of Answer objects, but in output i get everything beyond list of answers.
我尝试序列化包含问题列表的测验对象,女巫有 3 个字段:问题、分数和答案对象列表,但在输出中我得到了答案列表之外的所有内容。 My question is how to deal with it and why this is happening.
我的问题是如何处理它以及为什么会发生这种情况。
public class Quiz
{
public string Title;
public string Owner;
public string Version;
public string Descryption;
public List<Double> Wages;
public List<Question> Questions;
}
public class Question
{
public string Sentance { get; set; }
public int Score { get; set; }
List<Answer> answers;
}
public class Answer
{
public string text;
public bool isTrue;
}
// creating object Quiz and trying to serialize:
List<Double> wages = new List<Double>();
wages.Add(1);
wages.Add(0.5);
wages.Add(0.2);
Quiz quiz = new Quiz("testowy", "ja", "1.0", "Test quiz for checking serialization",wages);
List<Answer> tmpAnswers = new List<Answer>();
tmpAnswers.Add(new Answer("leg", true));
tmpAnswers.Add(new Answer("eye", false));
tmpAnswers.Add(new Answer("back", false));
tmpAnswers.Add(new Answer("chin", false));
quiz.Questions.Add(new Question("Question 1", 4, tmpAnswers));
tmpAnswers.Clear();
tmpAnswers.Add(new Answer("Kasia", false));
tmpAnswers.Add(new Answer("Andrzej", false));
tmpAnswers.Add(new Answer("Zenon", true));
tmpAnswers.Add(new Answer("Buba", false));
quiz.Questions.Add(new Question("Question 2", 3, tmpAnswers));
string json = JsonConvert.SerializeObject(quiz, Formatting.Indented);
Console.WriteLine(json);
//output
{
"Title": "testowy",
"Owner": "ja",
"Version": "1.0",
"Descryption": "Test quiz for checking serialization",
"Wages": [
1.0,
0.5,
0.2
],
"Questions": [
{
"Sentance": "jaka to jest część ciała?",
"Score": 4
}, // **Missing answers** //
{
"Sentance": "Kto to jest?",
"Score": 3
} // **Missing answers** //
]
}
Never mind.没关系。 Now i see there field list of answers is not public and it have to be for JsonConvert.
现在我看到答案的字段列表不是公开的,它必须用于 JsonConvert。
public class Question
{
public string Sentance { get; set; }
public int Score { get; set; }
public List<Answer> answers; // <----------
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.