dannyyy dannyyy - 6 months ago 10
JSON Question

How to serialize to this specific JSON format

I've a list of recipients as a list. How can I serialize the c# objects to this specific JSON format requested by mailgun?

C#

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


Expected JSON (According to 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" },
}


Using
JsonObject
and the serializable method
SimgpleJson.SerializeObject()
will produces JSON like this:

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

Answer

I think you can use following class to serialize the object

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

Output Json

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