如何将包含对象列表的对象列表序列化为JSON文件?

时间:2019-04-25 15:50:40

标签: c# serialization json.net

我正在编写简单的测验生成器,女巫将以json格式生成测验。我有3个班级作为额外的lib来管理所有测验。这些是:Quiz.cs,Question.cs和Answer.cs。我尝试序列化测验对象,女巫包含问题列表,女巫具有3个字段:问题,分数和答案对象列表,但是在输出中,我得到了答案列表以外的所有内容。我的问题是如何处理它以及为什么会这样。


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** //
  ]
}

1 个答案:

答案 0 :(得分:0)

没关系。现在,我看到那里的答案字段列表不是公开的,必须用于JsonConvert。

public class Question
    {
        public string Sentance { get; set; }
        public int Score { get; set; }
        public List<Answer> answers;            // <----------
         }