gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:29:39 25 4
gpt4 key购买 nike

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

// 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() 返回 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.

关于c# - 如何将 json 文件反序列化回从中序列化的通用列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com