我正在尝试使用Mailgun API创建一个电子邮件验证程序,但我仍然坚持阅读json响应。
这是我的代码:
foreach (string str in this.ema.Items)
{
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("https://api.mailgun.net/v3/address/validate?api_key=" + this.chei.Text + "&address=" + str);
httpWebRequest.ContentType = "application/json; charset=utf-8";
if (new StreamReader(httpWebRequest.GetResponse().GetResponseStream()).ReadToEnd().Contains(" \"mailbox_verification\": true"))
this.m_oWorker.ReportProgress(percentProgress, (object) str);
else
this.m_oWorker.ReportProgress(0, (object) str);
++percentProgress;
}
this.m_oWorker.ReportProgress(1);
}
这是json的回复:
{"address": "foo@mailgun.net",
"did_you_mean": null,
"is_disposable_address": false,
"is_role_address": true,
"is_valid": true,
"mailbox_verification": "true",
"parts": {
"display_name": null,
"domain": "mailgun.net",
"local_part": "foo"
}
注意“mailbox_verification”周围的引号:“true”,我认为我有错,但我不知道要解决它。
答案 0 :(得分:1)
可以轻松克服这种情况的一种方法是创建API响应模型,并使用Newtonsoft.Json
将JSON字符串反序列化到模型中。 mailbox_verification
将被解析为给定模型中显示的类型(在此实例中为bool
),这将为您提供您之后的显式类型。
<强>型号:强>
public class MailGunResponse
{
public string address { get; set; }
public string did_you_mean { get; set; }
public bool is_disposable_address { get; set; }
public bool is_role_address { get; set; }
public bool is_valid { get; set; }
public bool mailbox_verification { get; set; } //Make sure it is bool!
public Parts parts { get; set; }
}
public class Parts
{
public string display_name { get; set; }
public string domain { get; set; }
public string local_part { get; set; }
}
<强> Deserialise:强>
var json = File.ReadAllText("test.json"); //Change to you JSON string source.
var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<MailGunResponse>(json);