我有以下课程:
public class Student
{
public int studentNumber;
public string testWeek;
public string topics;
}
我做了一些事情,序列化并将其保存在文件中。它看起来像这样:
[
{
"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"
}
]
后来我想反序列化它,以便我可以再次处理它。我有这个代码
Student[] arr = new Student[numberOfStudentsInClass];
arr = JsonConvert.DeserializeObject<Student>(File.ReadAllText(_selectedClass))
其中_selectedClass是包含文件名的字符串。但是我收到了一个错误
无法将WindowsFormApplicationsForm1.Form.Student转换为WindowsFormApplicationsForm1.Form.Student []
答案 0 :(得分:4)
您在JsonConvert.DeserializeObject中指出您正在尝试反序列化为单个Student
实例。不是数组。并且无需在一个语句中初始化数组,然后在另一个语句中为其分配值。无论如何,我们现在通常使用通用数组。
替换:
Student[] arr = new Student[numberOfStudentsInClass];
arr = JsonConvert.DeserializeObject<Student>(File.ReadAllText(_selectedClass))
有了这个:
List<Student> students =
JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass));
答案 1 :(得分:3)
正如异常所述,方法public interface IRead<T>
{
T Read(bool[] binary);
int Key( T type );
}
public class Reader : IRead<int>, IRead<string>
{
int IRead<int>.Read( byte[] binary )
{
// does stuff
returns 4;
}
public int Key( int type ) { return 43; }
string IRead<string>.Read( byte[] binary )
{
// does stuff
returns "example";
}
public int Key( string type ) { return 61; }
static StreamProcessor( )
{
// Here I want to get the definitions
}
}
返回类型为JsonConvert.DeserializeObject<Student>
的对象,而变量Student
的类型为arr
。所以你可以&#t; t将Student[]
的结果分配给JsonConvert.DeserializeObject<Student>
。
您需要将文本反序列化为arr
,如果需要如下所示的数组,请调用List<Student>
:
.ToArray