将JSON从文件转换为列表<
本文关键字:列表 转换 文件 JSON | 更新日期: 2023-09-27 18:01:30
当试图从文件反序列化JSON时,我收到以下异常:Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List 1[Data.Models.Customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
我不知道为什么,因为我试图使用JArray。解析和JObject。解析文件。该文件当前只有一条记录,该记录如下所示:{"FirstName":"thatFirstName","LastName":"thatLastName","Address":{"Street":"mook","City":"sin city","State":"AL","ZipCode":"90989"},"Id":"9304b36a-f1a9-4cd5-91d0-282648104967"}
我遇到问题的代码如下:
JArray persistValues = null;
if(File.Exists(fileName))
{
FileInfo info = new FileInfo(fileName);
if (info.Length != 0)
{
persistValues = JArray.Parse(File.ReadAllText(fileName));
File.Delete(fileName);
}
}
... extraneous code ...
else if(className.Equals("customer"))
{
Customer customer = this as Customer;
customer.Id = Guid.NewGuid();
if (persistValues != null)
{
List<Customer> customers = persistValues.ToObject<List<Customer>>();
customers.Add(customer);
json = JsonConvert.SerializeObject(customers);
}
else
{
json = JsonConvert.SerializeObject(customer);
}
}
... extraneous code ...
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(json);
}
我错过了什么?我可以写入文件很好,但我无法读取和解析数据回到我的对象…
旁注:使用JArray时我收到的错误如下:
Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject.
看起来您只向文件写入单个Customer对象,而不是包含单个Customer的数组。Json。Net抱怨说,它希望找到一个数组来反序列化到List,但它只能找到一个Customer。
调用JsonConvert.SerializeObject(customers)将生成一个Json数组,因此请确保您开始使用的文件包含一个Customer数组,而不是单个序列化的Customer。
用Json序列化集合净