Skip to main content
 首页 » 编程设计

c#之哪个 Json 反序列化器呈现 IListT> 集合

2024年01月13日39小虾米

我正在尝试将 json 反序列化为对象模型,其中集合表示为 IList<T>类型。

真正的反序列化在这里:

JavaScriptSerializer serializer = new JavaScriptSerializer(); 
 
return serializer.Deserialize<IList<Contact>>( 
    (new StreamReader(General.GetEmbeddedFile("Contacts.json")).ReadToEnd())); 

在我发布异常之前,您应该知道什么是隐式转换。这是 Contact输入:

public class Contact 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public LazyList<ContactDetail> Details { get; set; } 
    //public List<ContactDetail> Details { get; set; } 
} 

这是 ContactDetail输入:

public class ContactDetail 
{ 
    public int ID { get; set; } 
    public int OrderIndex { get; set; } 
    public string Name { get; set; } 
    public string Value { get; set; } 
} 

了解 LazyList<T> 的重要事项是它实现了IList<T> :

public class LazyList<T> : IList<T> 
{ 
    private IQueryable<T> _query = null; 
    private IList<T> _inner = null; 
    private int? _iqueryableCountCache = null; 
 
 
    public LazyList() 
    { 
        this._inner = new List<T>(); 
    } 
 
    public LazyList(IList<T> inner) 
    { 
        this._inner = inner; 
    } 
 
    public LazyList(IQueryable<T> query) 
    { 
        if (query == null) 
            throw new ArgumentNullException(); 
        this._query = query; 
    } 

现在这个LazyList<T>在我尝试将 Json 反序列化到其中之前,类定义很好。 System.Web.Script.Serialization.JavaScriptSerializer似乎想将列表序列化为 List<T>这是有道理的,因为它的年龄,但我需要它们的类型 IList<T>所以他们会投进我的LazyList<T> (至少那是我认为我出错的地方)。

我得到这个异常:

System.ArgumentException: Object of type 'System.Collections.Generic.List`1[ContactDetail]' cannot be converted to type 'LazyList`1[ContactDetail]'.. 

当我尝试使用 List<ContactDetail> 时在我的 Contact类型(正如您在上面看到的评论)似乎有效。但我不想使用 List<T>的。我什至尝试过我的 LazyList<T>继承自 List<T>似乎执行但传递了 List<T>的内部 T[]对我的实现来说是一场噩梦,我根本不想要 List<T> 的膨胀我模型中的任何位置。

我也尝试了一些 other json库无济于事(我可能没有充分发挥它们的潜力。我或多或少地替换了引用并试图重复这个问题顶部引用的代码。也许传递设置参数会有帮助??)。

我现在不知道该尝试什么。我要用另一个反序列化器吗?我是否调整反序列化本身?我需要改变我的类型来取悦解串器吗?我是否需要更多地担心隐式转换或只实现另一个接口(interface)?

请您参考如下方法:

不可能直接反序列化到一个接口(interface),因为接口(interface)只是一个契约。 JavaScriptSerializer 必须反序列化为实现 IList 的具体类型,最合乎逻辑的选择是 List 。您必须将 List 转换为 LazyList,根据您发布的代码,这应该很容易:

var list = serializer.Deserialize<IList<Contact>>(...); 
var lazyList = new LazyList(list);