Convert List<string> to JSON using C# and Newtonsoft

Viewed 31472

I have a List that I would like to convert to JSON using C# and Newtonsoft.

tags

[0]: "foo"
[1]: "bar"

Output to be:-

{"tags": ["foo", "bar"]}

Can anybody point me in the right direction please? I can convert the List to JSON okay but they key thing here is I need the "tags" part in the JSON which I do not get with a convert using JsonConvert.SerializeObject(tags).

6 Answers

You could use this.

static void  Main(string[] args)
    {
        List<string> messages = new List<string>();
        messages.Add("test");
        messages.Add("test 2");
        Items data = new Items { items = messages };
        string output = JsonConvert.SerializeObject(data);
        JObject jo = JObject.Parse(output);
        Console.WriteLine(jo);
    }

public class Items
{
   public List<string> items { get; set; }
}

Produces:

{
  "items": [
    "test",
    "test 2"
  ]
}
Related