Deserialize serialized json CookieCollection

In my code, I have to Json serialize the CookieCollection and pass it as a string to achieve this. I like the following:

var json = Newtonsoft.Json.JsonConvert.SerializeObject(resp.Cookies); 

which leads to the next json

 [ { "Comment": "", "CommentUri": null, "HttpOnly": false, "Discard": false, "Domain": "www.site.com", "Expired": true, "Expires": "1970-01-01T03:30:01+03:30", "Name": "version", "Path": "/", "Port": "", "Secure": false, "TimeStamp": "2015-06-01T12:19:46.3293119+04:30", "Value": "deleted", "Version": 0 }, { "Comment": "", "CommentUri": null, "HttpOnly": false, "Discard": false, "Domain": ".site.com", "Expired": false, "Expires": "2015-07-31T12:19:48+04:30", "Name": "ADS_7", "Path": "/", "Port": "", "Secure": false, "TimeStamp": "2015-06-01T12:19:46.3449217+04:30", "Value": "0", "Version": 0 } ] 

To deserialize this json, I wanted to do something like this:

 var cookies = Newtonsoft.Json.JsonConvert.DeserializeObject<CookieCollection>(json); 

But it fails and raises a JsonSerializationException, saying

Cannot create and populate the list type System.Net.CookieCollection. Path '', line 1, position 1.

So, I changed my code to the next one and its work now

 var tmpcookies = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Cookie>>(json); CookieCollection cookies = new CookieCollection(); tmpcookies.ForEach(cookies.Add); 

I'm just wondering why my first attempt failed? and if there is a better way to do this.

+7
c # serialization json-deserialization
source share
1 answer

JSON.NET does not support deserialization of non-generic IEnumerable s.

CookieCollection implements IEnumerable and ICollection , but not IEnumerable<Cookie> . When JSON.NET proceeds to deserialize the collection, it does not know what to deserialize individual elements into IEnumerable in.

Contrast this with IList<Cookie> , which has a common parameter type. JSON.NET can determine the type of each item in the resulting list.

You can fix this using the workaround discussed in the comments, or write your own converter.

+3
source share

All Articles