【问题标题】:How to serialize object with list of objects containg list of objects to JSON file?如何使用对象列表序列化对象,其中包含对象列表到 JSON 文件?
【发布时间】:2019-04-25 15:50:40
【问题描述】:

我正在编写简单的测验生成器,女巫将生成 json 格式的测验。我有 3 个课程作为额外的库来管理所有测验。它们是: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** //
  ]
}

【问题讨论】:

    标签: c# serialization json.net


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多