我正在尝试使用 RestSharp 从 SendGrid 统计 API 的响应中反序列化 JSON。
请求成功,使用Fiddler我可以看到确实返回了响应。然而,当我尝试
var response = client.Execute<CMSEmailTrackingStatistic>(request);
我得到了 response.Data
的 null
这是我用来发出请求并接收响应的代码:
<!-- language: lang-cs -->
string trackingCategory = "E-News members 08-12-14";
string url = "/stats.get.json";
var client = new RestClient(ConfigurationManager.AppSettings["SendgridAPIUrl"]);
var request = new RestRequest(url, Method.POST);
request.AddParameter("category", trackingCategory, ParameterType.GetOrPost); // adds to POST or URL querystring based on Method
request.AddParameter("api_key", ConfigurationManager.AppSettings["SendGridPassword"], ParameterType.GetOrPost); // replaces matching token in request.Resource
request.AddParameter("api_user", ConfigurationManager.AppSettings["SendGridUserName"], ParameterType.GetOrPost);
request.AddParameter("aggregate", "1", ParameterType.GetOrPost);
var response = client.Execute<CMSEmailTrackingStatistic>(request);
return response.Data;
CMSEmailTrackingStatistic 类看起来像这样
public class CMSEmailTrackingStatistic
{
public int delivered { get; set; }
public int unsubscribes { get; set; }
public string name { get; set; }
public int invalid_email { get; set; }
public int bounces { get; set; }
public int repeat_unsubscribes { get; set; }
public int unique_clicks { get; set; }
public int spam_drop { get; set; }
public int repeat_bounces { get; set; }
public int repeat_spamreports { get; set; }
public int blocked { get; set; }
public int requests { get; set; }
public int spamreports { get; set; }
public int clicks { get; set; }
public int opens { get; set; }
public int unique_opens { get; set; }
}
这是从 SendGrid 发回的 JSON:
HTTP/1.1 200 OK
Server: nginx/1.4.7
Date: Thu, 14 Aug 2014 17:05:30 GMT
Content-Type: text/html
Connection: keep-alive
Access-Control-Allow-Origin: https://sendgrid.com
Content-Length: 328
[{"delivered": 7153, "unsubscribes": 0, "name": "E-News nonmembers 08-12-14", "invalid_email": 30, "bounces": 13, "repeat_unsubscribes": 0, "unique_clicks": 86, "spam_drop": 0, "repeat_bounces": 412, "repeat_spamreports": 31, "blocked": 14, "requests": 7665, "spamreports": 0, "clicks": 153, "opens": 1384, "unique_opens": 967}]
我尝试制作预期结果列表,但没有成功。
我已经联系了 SendGrid,因为我相信他们返回的 Content-Type 可能是一个问题(我也尝试过手动设置 Accept header )。
最佳答案
RestSharp
无法反序列化您的 JSON,因为它无效。
您的 JSON 以 [
开头,而不是包裹在里面的 {
,同样以 ]
结尾,而不是 }
当我删除括号时,我可以使用Json.NET
正确反序列化您的JSON(仅出于测试目的,没有理由这不应该与RestSharp
一起使用) ):
{
"delivered": 7153, "unsubscribes": 0, "name": "E-News nonmembers 08-12-14",
"invalid_email": 30, "bounces": 13, "repeat_unsubscribes": 0, "unique_clicks": 86,
"spam_drop": 0, "repeat_bounces": 412, "repeat_spamreports": 31, "blocked": 14,
"requests": 7665, "spamreports": 0, "clicks": 153, "opens": 1384, "unique_opens": 967
}
关于c# - RestSharp 反序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25313992/