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="[email protected]"/>

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": "[email protected]" }

But I want to see usual JSON array:

{ "name": "Incognito", "emails": [{"type": "Personal", "email": "[email protected]"}, {...}] }

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?

2
  • You would need to create a Model of type : List<emails> 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. Commented Mar 21, 2019 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 Commented Mar 21, 2019 at 12:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This should be a comment and not an actual answer. Please put code and more explanation on what you mean.
@RahulSharma Give me chance mate ;)
So, I need to put values in this model and then serialize? Do we have simple way to serialize app.config values to json array with using newtonsoft json?
@A.Gladkiy You would need to create a custom ConfigurationSection - see my comment on your question for an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.