8

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

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

resulting to the following 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 raise JsonSerializationException saying

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

So I changed my code to the following and its working now

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

I am just wondering why my first attempt fails? and if there is any nicer way of doing it.

HadiRj
  • 1,016
  • 3
  • 21
  • 37
  • As http://stackoverflow.com/questions/27449717/newtonsoft-json-cannot-create-and-populate-list-type says... Try to use List instead of CookieCollection. You can convert it to list by List cookieList = cookieCollection.OfType().ToList(); – Paul Zahra Jun 01 '15 at 07:54
  • @PaulZahra I already have it as List! my question is why this `Newtonsoft.Json.JsonConvert.DeserializeObject(json);` fails! – HadiRj Jun 01 '15 at 08:01
  • How is CookieCollection cookies = new CookieCollection(); the same as List ? – Paul Zahra Jun 01 '15 at 08:02
  • 1
    @har07 But List implements both IEnumerable (as well as IEnumerable) and ICollection which CoockieCollection implements too. – HadiRj Jun 01 '15 at 09:56

1 Answers1

3

JSON.NET doesn't support deserializing non-generic IEnumerables.

CookieCollection implements IEnumerable and ICollection, but not IEnumerable<Cookie>. When JSON.NET goes to deserialize the collection, it doesn't know what to deserialize the individual items in the IEnumerable into.

Contrast this with IList<Cookie> which has a generic type parameter. JSON.NET can determine what type each element in the resulting list should be.

You could fix this using the workaround discussed in the comments, or write a custom converter.

Andrew Whitaker
  • 119,029
  • 30
  • 276
  • 297