c# - Deserialize a json serialized CookieCollection -
in code have json serialize cookiecollection object , pass string, achieve this:
var json = newtonsoft.json.jsonconvert.serializeobject(resp.cookies);
resulting 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 json wanted this:
var cookies = newtonsoft.json.jsonconvert.deserializeobject<cookiecollection>(json);
but fails , raise jsonserializationexception saying
cannot create , populate list type system.net.cookiecollection. path '', line 1, position 1.
so changed code following , working now
var tmpcookies = newtonsoft.json.jsonconvert.deserializeobject<list<cookie>>(json); cookiecollection cookies = new cookiecollection(); tmpcookies.foreach(cookies.add);
i wondering why first attempt fails? , if there nicer way of doing it.
json.net doesn't support deserializing non-generic ienumerable
s.
cookiecollection
implements ienumerable
, icollection
, not ienumerable<cookie>
. when json.net goes deserialize collection, doesn't know deserialize individual items in ienumerable
into.
contrast ilist<cookie>
has generic type parameter. json.net can determine type each element in resulting list should be.
you fix using workaround discussed in comments, or write custom converter.
Comments
Post a Comment