首页 > 解决方案 > List的Json-反序列化失败:该类型需要一个 JSON 数组才能正确反序列化

问题描述

我正在开发一个 Xamarin.Forms 应用程序,当没有可用的 Internet 连接时,我需要在其中缓存数据。我目前正在使用内置的Application.Current.Properties持久性机制来持久化数据,效果很好。但是,对于更复杂的对象,我无法反序列化。

我有以下对象模型:

public class SPL
{
    public SPL(Point point, Location location)
    {
        Point = point;
        Location = location;
    }

    public Location Location { get; set; }
    public Point Point { get; set; }
}

whereLocation有两个 type属性,分别有 typedouble和type两个属性。PointDateTimedouble

通过应用程序的执行时间,只要没有可用的互联网连接,我就会像这样将数据持续保存在本地缓存中

SPL spl = new SPL(point, location);
SPLValues.Add(spl);
var serializedSpl = JsonConvert.SerializeObject(SPLValues);
Application.Current.Properties["splvalues"] = serializedSpl;

在最后一行中断并使用调试器检查显示数据持久的。

当应用程序进入睡眠状态时,我调用Current.SavePropertiesAsync();. 恢复应用程序后,我尝试像这样反序列化本地缓存

public List<T> GetCache<T>(string key) where T : class
{
    IDictionary<string, object> properties = Application.Current.Properties;
    if (properties.ContainsKey(key))
    {
        var data = JsonConvert.DeserializeObject<List<T>>(key); // Fails here
        return data;
    }
    return new List<T>();
}

哪个失败了。抛出的异常是

未处理的异常:Newtonsoft.Json.JsonReaderException:解析值时遇到意外字符:s。路径 '',第 0 行,第 0 位置。发生

更新

正如 JOSEFtw 所指出的,我在反序列化调用中缺少一个参数,所以它现在看起来像这样:var data = JsonConvert.DeserializeObject<List<T>>(properties[key]);

修复此问题后,我现在遇到此错误:

未处理的异常:Newtonsoft.Json.JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[CacheDemo.Models.SPL]' 因为类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。路径“位置”,第 1 行,位置 12。发生

我究竟做错了什么?

标签: c#json-deserialization

解决方案


我认为你应该反序列化

properties[key] 

代替

key

像这样

var data = JsonConvert.DeserializeObject<List<T>>(properties[key]); 

推荐阅读