将JSON从文件转换为List <t>

时间:2016-08-09 23:58:53

标签: c# json

尝试从文件反序列化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.Parse和JObject.Parse。该文件目前只有一条记录,该记录如下所示:
{"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.

1 个答案:

答案 0 :(得分:0)

看起来您只将一个Customer对象写入您的文件,而不是只包含一个Customer的数组。 Json.Net抱怨说,它希望找到一个数组,以便对列表进行derserialize,但它只能找到一个客户。

调用JsonConvert.SerializeObject(customers)将生成一个Json数组,因此请确保您开始使用的文件包含一个Customer数组而不是一个序列化客户。

Serializing collections with Json.Net