使用C#在JSON中解析Campaign Monitor的HTTP POST请求

时间:2015-01-19 15:42:43

标签: c# asp.net json webhooks campaign-monitor

基本上我正在使用Campaign Monitor的webhook。我创建了一个更新webhook,因此当更新电子邮件时,Campaign Monitor会将HTTP POST请求发送到我指定的URL。我在解析JSON时遇到问题。

这是:

POST /subscribe HTTP/1.1
Host: example.com:80
Accept: */*
Content-Type: application/json
{
    "Events": [
        {
            "CustomFields": [
                {
                    "Key": "website", 
                    "Value": "http:\/\/example.org"
                }
            ],
           "Date": "2010-12-14 11:32:00",
           "OldEmailAddress": "test@example.org",
           "EmailAddress": "test@example.org",
           "Name": "Test Subscriber Renamed",
           "Type": "Update",
           "State": "Active"
        }
    ],
    "ListID": "96c0bbdaa54760c8d9e62a2b7ffa2e13"
}

我查看了示例http://msdn.microsoft.com/en-ca/library/cc197957(v=vs.95).aspx,但无法解决这个问题。

我想获取OldEmailAddress,EmailAddress,Type和State。谢谢,

参考Campaign Monitor的webhooks https://www.campaignmonitor.com/api/webhooks/#currently_available_webhooks

谢谢,

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你会尝试使用C#从url获取json数据。首先,您需要获取名为Newtonsoft.Json的NuGet包

然后你可以使用这段代码

using (HttpClient client = new HttpClient())
{

  client.BaseAddress = new Uri("http://yourapisite.com"); // Not whole link, just host

  var url = "link after your host url";

  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

  HttpResponseMessage response = await client.GetAsync(url);

  if (response.IsSuccessStatusCode)
  {
     var data = response.Content.ReadAsStringAsync();
     YourClass responsedata = JsonConvert.DeserializeObject<YourClass>(data.Result.ToString());



  }

}

希望得到这个帮助。

修改 首先,Newtonsoft对反序列化json非常敏感。像CustomField这样的每个json属性都有一个同名的属性。我编辑了你的代码答案。请检查并告诉我它是如何工作的。

我无法调试此代码,因为我不知道你的api url。

public class Events {
    public Events()
    {
        this.eventData = new List<EventData>();
    }
    public string ListID { get; set; } 
    public List<EventData> eventData { get; set; } 
}
public class EventData {
    public EventData()
    {
        this.CustomFields = new List<CustomFields>();
    }
    public DateTime Date { get; set; }
    public string OldEmailAddress { get; set; }
    public string EmailAddress { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string State { get; set; }

    public List<CustomFields> CustomFields { get; set; }

}
public class CustomFields
{
    public string Key { get; set; }
    public string Value { get; set; }
}