'Convert List<string> to JSON using C# and Newtonsoft
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).
Solution 1:[1]
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 2:[2]
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 3:[3]
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"));
Solution 4:[4]
You can use anonymous object to wrap your list like that:
JsonConvert.SerializeObject(new {Tags = tags});
Solution 5:[5]
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"
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jamiec |
| Solution 2 | Vishwash Roy |
| Solution 3 | Antonyo |
| Solution 4 | Krzysztof Skowronek |
| Solution 5 | Joe Gurria Celimendiz |
