我收到 JSON 格式的回复。我正在使用 jsSerializer 从 JSON 中获取字段的值。它大部分都在工作,但我不确定为什么在一种情况下返回的 JSON 包含\n
在其中,因此,jsSerializer 无法正常工作。
这是我的代码:
protected void btnStats_Click(object sender, EventArgs e)
{
IRestResponse response = GetStats();//Stats provide you with the summary of the events that occur with your messages.
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var jsobj = jsSerializer.Deserialize<dynamic>(response.Content);
int total_count= Convert.ToInt32(jsobj[0]["total_count"]); //I am getting error
这是返回 JSON 的方法:
public static IRestResponse GetStats()
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator =
new HttpBasicAuthenticator("api",
"key");
RestRequest request = new RestRequest();
request.AddParameter("domain",
"messenger.test.com", ParameterType.UrlSegment);
request.Resource = "{domain}/stats";
request.AddParameter("event", "sent");
request.AddParameter("event", "opened");
request.AddParameter("skip", 1);
request.AddParameter("limit", 2);
return client.Execute(request);
}
我有几种工作正常的方法,我发现的唯一区别是 ( response.Content
) 中的 JSON 格式\n
。我没有做任何事情来删除\n
;它只是不存在。
这是我从该代码中得到的 JSON:
"{\n \"total_count\": 54,\n \"items\": [\n {\n \"total_count\": 715,\n \"created_at\": \"Mon, 04 Nov 2013 00:00:00 GMT\",\n \"tags\": {},\n \"id\": \"5276e3835b8917d8268a6df1\",\n \"event\": \"opened\"\n },\n {\n \"total_count\": 688,\n \"created_at\": \"Sun, 03 Nov 2013 00:00:00 GMT\",\n \"tags\": {},\n \"id\": \"527592035b8917d8268a1348\",\n \"event\": \"sent\"\n }\n ]\n}"
在另一种工作正常的方法中,我得到了这种 JSON:
"[{\"unique\": {\"link\": 1}, \"total\": 35, \"recipient\": \"cutesycanvas@gmail.com\"}, {\"unique\": {\"link\": 1}, \"total\": 22, \"recipient\": \"angelina40d@hotmail.com\"}]"