如何使用Mailgun webhook从邮件头解析JSON数组

时间:2013-06-14 02:44:04

标签: c# json servicestack mailgun

来自mailgun回调的一组典型邮件头如下所示:

[["Received", "by luna.mailgun.net with SMTP mgrt 8765806286401; Fri, 14 Jun 2013 02:25:33 +0000"],
["Content-Type", ["multipart/mixed", {"boundary": "199d7350597e43c0af0e4c814b8a35af"}]],    
["Mime-Version", "1.0"], 
["Subject", "Test Message"],
["From", "Test Sender <sender@mydomain.com>"],
["To", "Test Receiver <receiver1@mydomain.com>"],
["Reply-To", "replyto@mydomain.com"], 
["Message-Id", "<20130614022533.18419.66130@mydomain.com>"], 
["X-Mailgun-Sid", "WyIzOTUwOCIsICJuZWlsLmRvYnNvbkBleGFsdGdyb3VwLmNvbS5hdSIsICI4ZjY3OCJd"], 
["Date", "Fri, 14 Jun 2013 02:25:33 +0000"], 
["Sender", "sender@mydomain.com"]]

我认为这会反序列化为键/值对列表,但我无法使其正常工作。显然,Content-Type项目更复杂。

任何人都可以帮助使用ServiceStack或内置的.NET反序列化器将其解析为列表或poco吗?

1 个答案:

答案 0 :(得分:3)

不幸的是,第三方API在[[“key”,“value”],...]数组中返回JSON而不是{“key:”value“,...}。后者会很多更容易解析成这样的典型类:

public class Foo
{
    public string Received {get; set;}
    [DataMember(Name = "Content-Type")]
    public string ContentType {get; set;}
    ... 
}

它返回的方式是一个匿名的值列表,包含更多的匿名列表,其中0值是键,1值是值。

我没有尝试过,但你可能想尝试反序列化为匿名类型的动态列表,每this SO answer

List<JsonObject> jsonObject = JsonArrayObjects.Parse(json);
jsonObject.PrintDump(); // show data

然后为方便起见,您可以编写一个映射例程来将jsonObject复制到更易读的类。

更新:我写了一些代码来测试。不是那么漂亮,但它确实可以按原样访问解析的JSON。

string json = @"[[""Received"", ""by luna.mailgun.net with SMTP mgrt 8765806286401; Fri, 14 Jun 2013 02:25:33 +0000""],
[""Content-Type"", [""multipart/mixed"", {""boundary"": ""199d7350597e43c0af0e4c814b8a35af""}]],    
[""Mime-Version"", ""1.0""], 
[""Subject"", ""Test Message""],
[""From"", ""Test Sender <sender@mydomain.com>""],
[""To"", ""Test Receiver <receiver1@mydomain.com>""],
[""Reply-To"", ""replyto@mydomain.com""], 
[""Message-Id"", ""<20130614022533.18419.66130@mydomain.com>""], 
[""X-Mailgun-Sid"", ""WyIzOTUwOCIsICJuZWlsLmRvYnNvbkBleGFsdGdyb3VwLmNvbS5hdSIsICI4ZjY3OCJd""], 
[""Date"", ""Fri, 14 Jun 2013 02:25:33 +0000""], 
[""Sender"", ""sender@mydomain.com""]]";

List<JsonObject> jsonObject = JsonArrayObjects.Parse(json);
// jsonObject.PrintDump(); // show data

string received = jsonObject[0].Values.First();
string contentType = jsonObject[1].Values.First();
List<JsonObject> contentTypeValues = JsonArrayObjects.Parse(jsonObject[1].Values.First());
string boundary = contentTypeValues[1].Values.First();
string mimeVersion = jsonObject[2].Values.First();

Console.WriteLine(string.Format("received: {0}", received));
Console.WriteLine(string.Format("contentType: {0}", contentType));
Console.WriteLine(string.Format("boundary: {0}", boundary));
Console.WriteLine(string.Format("mimeVersion: {0}", mimeVersion));