简体   繁体   English

使用Newtonsoft JSON反序列化的问题

[英]Problems deserializing using Newtonsoft JSON

I have the following class: 我有以下课程:

public class Student
{
    public int studentNumber;
    public string testWeek;
    public string topics;
}

I do some stuff to it, serialize it and save it in a file. 我对它做了一些处理,对其进行序列化并将其保存在文件中。 It looks likes this: 看起来像这样:

[
  {
    "studentNumber": 1,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 2,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 3,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 4,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 5,
    "testWeek": "1",
    "topics": "5 & 8"
  }
]

Later I want to deserialize it so I can work on it again. 稍后,我想对其进行反序列化,以便再次进行处理。 I have this code 我有这个代码

Student[] arr = new Student[numberOfStudentsInClass];
arr = JsonConvert.DeserializeObject<Student>(File.ReadAllText(_selectedClass))

Where _selectedClass is string containing the file name. 其中_selectedClass是包含文件名的字符串。 But I am getting an error 但是我遇到一个错误

Cannot convert WindowsFormApplicationsForm1.Form.Student to WindowsFormApplicationsForm1.Form.Student[] 无法将WindowsFormApplicationsForm1.Form.Student转换为WindowsFormApplicationsForm1.Form.Student []

You indicated in your JsonConvert.DeserializeObject that you are trying to deserialize to a single Student instance. 您在JsonConvert.DeserializeObject中指示要尝试反序列化为单个Student实例。 Not an array. 不是数组。 And there's no need to initialize the array in one statement and then assign it a value on another. 而且,无需在一个语句中初始化数组,然后在另一个语句上为其分配值。 And anyways, we generally use generic arrays these days. 而且无论如何,这些天我们通常使用通用数组。

Replace: 更换:

Student[] arr = new Student[numberOfStudentsInClass];
arr = JsonConvert.DeserializeObject<Student>(File.ReadAllText(_selectedClass))

With this: 有了这个:

List<Student> students = 
     JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass));

As the exception states, the method JsonConvert.DeserializeObject<Student> returns an object of type Student , while the variable arr is of type Student[] .so you can't assign the result of JsonConvert.DeserializeObject<Student> to arr . 作为异常状态,方法JsonConvert.DeserializeObject<Student>返回类型为Student的对象,而变量arr的类型为Student[] ,因此您无法将JsonConvert.DeserializeObject<Student>的结果分配给arr

you need to Deserialize your text to a List<Student> instead and call .ToArray if you want an array such as follows: 您需要将文本反序列.ToArray List<Student> ,如果需要数组,请调用.ToArray ,如下所示:

Student[] students = JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass)).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM