shakedong93
shakedong93

Reputation: 61

Serialize JSON with numbers as property names

How can I serialize a DataTable which contains a list of phone numbers, BodyOverride and ChannelType to this structure? The final JSON should look like the sample below. I see some posts that suggest using a Dictionary, but not I'm not sure if I can achieve this.

{
  "Addresses": {
    "+1713XXXXXXX": {
      "BodyOverride": "sent",
      "ChannelType": "SMS"
    },
    "+1832XXXXXXX": {
      "BodyOverride": "this is a text from PINPOINT",
      "ChannelType": "SMS"
    }
  }
}

Upvotes: 0

Views: 1008

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129687

Try a using class structure like this:

public class Payload
{
    public Dictionary<string, Item> Addresses { get; set; }
}

public class Item
{
    public string BodyOverride { get; set; }
    public string ChannelType { get; set; }
}

Assuming you are starting from a DataTable that looks like this:

DataTable dataTable = new DataTable();
dataTable.Columns.Add("Address");
dataTable.Columns.Add("BodyOverride");
dataTable.Columns.Add("ChannelType");
dataTable.Rows.Add("+1713XXXXXXX", "sent", "SMS");
dataTable.Rows.Add("+1832XXXXXXX", "this is a text from PINPOINT", "SMS");

...you can easily convert it to the desired class structure like this:

var payload = new Payload
{
    Addresses = dataTable.Rows
        .Cast<DataRow>()
        .ToDictionary(row => (string)row["Address"],
                      row => new Item
                      {
                          BodyOverride = (string)row["BodyOverride"],
                          ChannelType = (string)row["ChannelType"]
                      })
};

...and finally serialize it to JSON using a decent serialization library like Json.Net:

string json = JsonConvert.SerializeObject(payload, Formatting.Indented);

Fiddle: https://dotnetfiddle.net/b7Ckzs

Important note: the above solution assumes that the phone numbers in the Address column will be distinct across all rows in the DataTable. If they are not, then this solution will not work, because dictionary keys are required to be unique. In that case you will need to split the data into multiple batches, or find some other solution to deal with duplicates.

Upvotes: 2

Related Questions