如何将 json 文件反序列化回从中序列化的通用列表?

How can I deserialize a json file back into the generic list from which it was Serialized?

我正在使用 JSON.NET 将通用列表序列化为 json 文件。它工作正常,但我不知道如何逆转这个过程 - 读入 json 文件并用其内容扩充通用列表。

我有一个很简单的class:

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 文件并将内容读回通用列表。到目前为止我唯一得到的是:

// 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'

完成此任务的正确方法是什么?

Deserialize JSON from a file,您可以将文件加载到字符串中,然后反序列化:

    var jsonContents = System.IO.File.ReadAllText(ASSIGNMENT_TYPES_FILENAME);
    assignmentTypesList = JsonConvert.DeserializeObject<List<AssignmentTypesLU>>(jsonContents);

或者直接从流反序列化:

    using (var reader = System.IO.File.OpenText(ASSIGNMENT_TYPES_FILENAME))
    using (var jsonReader = new JsonTextReader(reader))
    {
        var serializer = JsonSerializer.CreateDefault();
        assignmentTypesList = serializer.Deserialize<List<AssignmentTypesLU>>(jsonReader);
    }

File.ReadLines() returns 一个 IEnumerable<string>。没有 Deserialize 重载来反序列化可枚举的字符串。

对于大文件,直接流式传输会更高效。来自 Json.NET: Performance Tips

To minimize memory usage and the number of objects allocated, Json.NET supports serializing and deserializing directly to a stream. Reading or writing JSON a piece at a time, instead of having the entire JSON string loaded into memory, is especially important when working with JSON documents greater than 85kb in size to avoid the JSON string ending up in the large object heap.