如何用Mailgun webhook从消息头解析JSON数组
本文关键字:JSON 数组 消息 何用 Mailgun webhook | 更新日期: 2023-09-27 18:18:25
来自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项要复杂得多。
谁能帮助解析这个列表或poco使用ServiceStack或内置的。NET反序列化器?
很不幸,第三方API返回JSON [["key","value"],…]数组,而不是{"key:"value",…}。后者更容易解析为典型的类,像这样:
public class Foo
{
public string Received {get; set;}
[DataMember(Name = "Content-Type")]
public string ContentType {get; set;}
...
}
它返回的方式是一个值的匿名列表,包含更多的匿名列表,其中0值是键,1值是值。
我还没有尝试过,但你可能想尝试反序列化到匿名类型的动态列表,根据这个SO答案
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));