如何序列化为此特定JSON格式

时间:2016-06-01 09:50:26

标签: c# json serialization json.net mailgun

我列出了收件人列表。如何将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-sending

{
   "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" }},
    ]
}

3 个答案:

答案 0 :(得分:1)

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

<?php 
$video = $_GET['video']; 
$videodata = $pdo->prepare("SELECT * FROM video WHERE site url =:siteurl LIMIT 1"); // check db for :siteurl value

$videodata->bindParam(':siteurl', $_GET['video'], PDO::PARAM_STR); // bind site url to $_Get Value...

$videodata->execute([$video]); // execute

if($videodata->rowCount()) { // If videodata [url string] returns data then... 
 echo '<b>hello world... this entry is there!</b>';
 } else {
 echo 'NO .... ITS NOT THERE';
 }
;
?>

或者这个:

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

答案 1 :(得分:1)

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

 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"
    }
}

答案 2 :(得分:0)

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

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

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; }
}