在我的代码中,我需要将CookieCollection对象进行Json序列化并作为字符串传递,我是这样做的:
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);
我想知道为什么我的第一次尝试失败了?是否有更好的方法可以实现它?
Newtonsoft.Json.JsonConvert.DeserializeObject<CookieCollection>(json);
会失败! - HadiRj