代码之家  ›  专栏  ›  技术社区  ›  Lechucico

将JSON解析为对象数组[重复]

  •  0
  • Lechucico  · 技术社区  · 8 年前

    这个问题已经有了答案:

    我有以下序列化类:

    [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加载一组问题?

    3 回复  |  直到 8 年前
        1
  •  1
  •   huckjulius    8 年前

    可以使用newtonsoft.json对对象进行序列化和反序列化。它很容易使用。我想你必须安装Nuget软件包。

    以下是关于如何在Unity 3D中序列化和保存数据的文章: Post

        2
  •  1
  •   Aydin    8 年前

    这是一个有效的例子

    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);
    

    enter image description here

        3
  •  0
  •   Ryan Wilson    8 年前

    你可以用 NewtonSoft.Json.JsonConvert.SerializeObject 和 Newtonsoft.Json.JsonConvert.DeserializeObject<T> 如果你有那个 nuget package 安装。然后用一个 JsonProperty 标签、文件( https://www.newtonsoft.com/json/help/html/SerializingJSON.htm )