我正在使用JSON.NET將通用列表序列化爲json文件。它工作正常,但我不知道如何反轉這個過程 - 在json文件中讀取並用其內容填充泛型列表。如何反序列化一個json文件回到序列化的通用列表中?
我有一個非常簡單的類:
public class AssignmentTypesLU
{
public int AssignmentID { get; set; }
public string AssignmentName { get; set; }
}
...和通用的列表來保存它的實例:
List<AssignmentTypesLU> assignmentTypesList;
我再填充泛型列表,如果該文件已經不存在(理論上,條件是隻有一次):
if (!System.IO.File.Exists(ASSIGNMENT_TYPES_FILENAME))
{
List<AssignmentTypesLU> atluList = new List<AssignmentTypesLU>();
AssignmentTypesLU atlu = new AssignmentTypesLU();
atlu.AssignmentID = 1;
atlu.AssignmentName = "Bible Reading";
atluList.Add(atlu);
atlu = new AssignmentTypesLU();
atlu.AssignmentID = 2;
atlu.AssignmentName = "Initial Call";
atluList.Add(atlu);
. . .
// Serialize contents of list to json file
var jsonAssignmentTypesLU = JsonConvert.SerializeObject(atluList);
System.IO.File.WriteAllText(ASSIGNMENT_TYPES_FILENAME, jsonAssignmentTypesLU);
}
但我想打開json文件和rea d將內容返回到通用列表中。到目前爲止,我所擁有的唯一的事情是:
// Now open these files and read their contents into the lists declared above.
if (System.IO.File.Exists(ASSIGNMENT_TYPES_FILENAME))
{
var jsonContents = System.IO.File.ReadLines(ASSIGNMENT_TYPES_FILENAME);
assignmentTypesList = JsonConvert.DeserializeObject<List<AssignmentTypesLU>>(jsonContents);
}
...但與(誠然,那種胡亂猜測的)我得到的,「無法從‘System.Collections.Generic.IEnumerable’轉換爲'string'「
完成此操作的正確方法是什麼?
你能告訴我們一個json文件的片段嗎? –
[{「AssignmentID」:1,「AssignmentName」:「Bible Reading」},{「AssignmentID」:2,「AssignmentName」:「Initial Call」},{「AssignmentID」:3,「AssignmentName」:「 Householder「},{」AssignmentID「:4,」AssignmentName「:」返回訪問「},{」AssignmentID「:5,」AssignmentName「:」返回訪問Householder「},{」AssignmentID「:6,」AssignmentName「: 「查經」},{「AssignmentID」:7,「AssignmentName」:「聖經學習之家」}] –