Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# List<string> to JSON objects

I have a list of strings, printing out:

["TEST1","TEST2","TEST3"]

How would I go about transforming this data to this JSON formatting?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{
"value": "TEST1"
},
{
"value": "TEST2"
},
{
"value": "TEST3"
}
]

I do not plan on creating an object.

Have tried using dictionary and key value pairs as well.

>Solution :

you can try this

List<string> tests = new List<string> { "TEST1", "TEST2", "TEST3"};

string json = JsonConvert.SerializeObject( tests.Select( t=> new { value = t }));

but I highly recommend to create a class

string json = JsonConvert.SerializeObject( tests.Select( t => new Test { value = t}));

   // or if you are using System.Text.Json
string json = JsonSerializer.Serialize(tests.Select(  t=>n ew Test { value = t }));
    
public class Test
{
    public string value {get; set;}
}

json

[{"value":"TEST1"},{"value":"TEST2"},{"value":"TEST3"}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading