Which Json deserializer renders IList collections?

前端 未结 3 647
别跟我提以往
别跟我提以往 2021-02-06 18:51

I\'m trying to deserialize json to an object model where the collections are represented as IList types.

The actual deserializing is here:

相关标签:
3条回答
  • 2021-02-06 19:09

    I ended up using the Json.NET lib which has good linq support for custom mapping. This is what my deserializing ended up looking like:

            JArray json = JArray.Parse(
                (new StreamReader(General.GetEmbeddedFile("Contacts.json")).ReadToEnd()));
    
            IList<Contact> tempContacts = (from c in json
                                           select new Contact
                                           {
                                               ID = (int)c["ID"],
                                               Name = (string)c["Name"],
                                               Details = new LazyList<ContactDetail>(
                                                   (
                                                       from cd in c["Details"]
                                                       select new ContactDetail
                                                       {
                                                           ID = (int)cd["ID"],
                                                           OrderIndex = (int)cd["OrderIndex"],
                                                           Name = (string)cd["Name"],
                                                           Value = (string)cd["Value"]
                                                       }
                                                    ).AsQueryable()),
                                               Updated = (DateTime)c["Updated"]
                                           }).ToList<Contact>();
    
            return tempContacts;
    
    0 讨论(0)
  • 2021-02-06 19:19

    It is not possible to deserialize directly to an interface, as interfaces are simply a contract. The JavaScriptSerializer has to deserialize to some concrete type that implements IList<T>, and the most logical choice is List<T>. You will have to convert the List to a LazyList, which given the code you posted, should be easy enough:

    var list = serializer.Deserialize<IList<Contact>>(...);
    var lazyList = new LazyList(list);
    
    0 讨论(0)
  • 2021-02-06 19:28

    Unfortunately you will probably need to fix your class, as there is no way for a deserializer to know that it should be of type IList, since List is an implementation of IList.

    Since the deserializers at http://json.org have source available you could just modify one to do what you want.

    0 讨论(0)
提交回复
热议问题