如何序列化为这种特定的JSON格式



我有一个收件人列表。如何将c#对象序列化为mailgun请求的特定JSON格式?

C#

var recipients = new List<Recipient>
{
new Recipient("test1@foo.com", "Foo Bar 1", "1234"),
new Recipient("test2@foo.com", "Foo Bar 2", "9876"),
...
}

预期的JSON(根据https://documentation.mailgun.com/user_manual.html#batch-发送)

{
"test1@foo.com": { "name": "Foo Bar 1", "customerNumber": "1234" },
"test2@foo.com": { "name": "Foo Bar 2", "customerNumber": "9876" },
}

使用JsonObject和可序列化方法SimgpleJson.SerializeObject()将生成如下JSON:

{
[
{"test1@foo.com": { "name": "Foo Bar 1", "customerNumber": "1234" }},
{"test2@foo.com": { "name": "Foo Bar 2", "customerNumber": "9876" }},
]
}

我认为您可以使用以下类来序列化对象

public class Test1FooCom
{
public string name { get; set; }
public string customerNumber { get; set; }
}

var obj = new Dictionary<string, Test1FooCom>
{
{"test1@foo.com", new Test1FooCom(){name="Foo Bar 1",customerNumber="1234"}},
{"test2@foo.com", new Test1FooCom(){name="Foo Bar 2",customerNumber="9876"}},        
};
var json = JsonConvert.SerializeObject(obj);

输出Json

{  
"test1@foo.com":{  
"name":"Foo Bar 1",
"customerNumber":"1234"
},
"test2@foo.com":{  
"name":"Foo Bar 2",
"customerNumber":"9876"
}
}

您应该为预期的JSON使用Dictionary,如下所示:

var recipients = new Dictionary<string, Recipient>
{
{"test1@foo.com", new Recipient("Foo Bar 1", "1234")},
{"test2@foo.com", new Recipient("Foo Bar 2", "9876")},
...
}

或者这个:

var recipients = new Dictionary<string, object>
{
{"test1@foo.com", new  {name = "Foo Bar 1", customerNumber = "1234"}},
{"test2@foo.com", new  {name = "Foo Bar 2", customerNumber = "9876"}}
};
Debug.WriteLine(recipients.ToJson());

实际结果是正确的。收件人列表立即转换为数组构造[],因此此列表中的任何内容都将显示为实际输出中的内容。

你的期望不会起作用,因为它会反序列化回ths:

public class Rootobject
{
public Test1FooCom test1foocom { get; set; }
public Test2FooCom test2foocom { get; set; }
}
public class Test1FooCom
{
public string name { get; set; }
public string customerNumber { get; set; }
}
public class Test2FooCom
{
public string name { get; set; }
public string customerNumber { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新