2

I have some parameters in app.config file of my project. I want to do these parameters as simple as possible for customers

<add key="name" value="Incognito"/>
<add key="emails[0].type" value="Personal"/>
<add key="emails[0].email" value="abc@abc.com"/>

I need to do JSON from these parameters. For now I use Dictionary

var parameters = new Dictionary<string, string>();
for (int i = 0; i < settings.Count; i++)
{
    parameters.Add(settings.GetKey(i), settings[i]);
}
var jsonData = JsonConvert.SerializeObject(parameters);

In that case I have in result:

{ "name": "Incognito", "emails[0].type": "Personal", "emails[0].email": "abc@abc.com" }

But I want to see usual JSON array:

{ "name": "Incognito", "emails": [{"type": "Personal", "email": "abc@abc.com"}, {...}] }

How can I do that? How serialize it properly? Or maybe you know a way to write data in app.config in human readable format?

phuzi
  • 12,078
  • 3
  • 26
  • 50
A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82
  • You would need to create a Model of type : **List** with emails having two properties: **type** and **email** respectively. Then you would need to set these properties in your dictionary. Then a simple serialization would give you your result. – Rahul Sharma Mar 21 '19 at 11:55
  • 2
    If you've more than a few settings in app/web.config like this which are closely related, it may be worth looking in to [creating a custom ConfigurationSection](https://stackoverflow.com/a/3936194/592958) – phuzi Mar 21 '19 at 12:05

1 Answers1

4

To get a JSON array you'll need to use something more like an array, say perhaps an Array or List of a type which has both type and email properties.

public class Parameters{
    public string Name { get; set; }
    public List<Email> Emails { get; set; }
}

public class Email{
    public string Type { get; set; }
    public string Email { get; set; }
}

Serialising an instance of Parameters will get you the JSON structure you desire.

phuzi
  • 12,078
  • 3
  • 26
  • 50