在我的代码中,我必须 Json 序列化一个 CookieCollection 对象并将其作为字符串传递,为了实现这一点,我这样做:
var json = Newtonsoft.Json.JsonConvert.SerializeObject(resp.Cookies);
导致以下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
}
]
为了反序列化这个 json,我想做这样的事情:
var cookies = Newtonsoft.Json.JsonConvert.DeserializeObject<CookieCollection>(json);
但它失败并引发JsonSerializationException说
无法创建和填充列表类型 System.Net.CookieCollection。路径'',第 1 行,位置 1。
所以我将我的代码更改为以下代码,它现在可以工作了
var tmpcookies = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Cookie>>(json);
CookieCollection cookies = new CookieCollection();
tmpcookies.ForEach(cookies.Add);
我只是想知道为什么我的第一次尝试失败了?以及是否有更好的方法。