2016-04-15 37 views
0

我有下面的類反序列化:問題使用Newtonsoft JSON

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 []

回答

3

作爲異常狀態,JsonConvert.DeserializeObject<Student>返回Student類型的對象的方法中,而可變arrStudent[]類型的。所以可以將JsonConvert.DeserializeObject<Student>的結果分配給arr

您需要將文字反序列化到List<Student>代替,並呼籲.ToArray如果你想要一個陣列,如下:

Student[] students = JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass)).ToArray(); 
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)); 
+0

謝謝。我以前一直在將數據作爲一個數組進行處理,但也許列表可能會更好。時間開始重寫! – Luves2spooge