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

25,979

Solution 1

The below code wraps the list in an anonymous type, and thus generates what you are looking for.

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<string> {"foo", "bar"};

            var tags = new {tags = list};

            Console.WriteLine(JsonConvert.SerializeObject(tags));

            Console.ReadLine();
        }
    }
}

Solution 2

Arguably the easiest way to do this is to just write a wrapper object with your List<string> property

public class Wrapper
{
    [JsonProperty("tags")]
    public List<string> Tags {get; set; }
}

And then when serialized this gives the output you expect.

var obj = new Wrapper(){ Tags = new List<string>(){ "foo", "bar"} };
var json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
// outputs: {"tags":["foo","bar"]}

Live example: http://rextester.com/FTFIBT36362

Solution 3

Use like this.

var data = new { tags = new List<string> { "foo", "bar" } };
var str = Newtonsoft.Json.JsonConvert.SerializeObject(data);

Output:

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

Hope this helps.

Solution 4

Create a separate class like this:

public class TagList
{
    [JsonProperty("tags")]
    List<string> Tags { get; set; }

    public TagList(params string[] tags)
    {
        Tags = tags.ToList();
    }
}

Then call:

JsonConvert.SerializeObject(new TagList("Foo", "Bar"));
Share:
25,979
chillifoot
Author by

chillifoot

Updated on July 09, 2022

Comments

  • chillifoot
    chillifoot almost 2 years

    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).