Convert a string list to json format

advertisements

How to convert a list of string

 List<string> keys = new List<string>() { "1-12VEXP", "1-124DH9"};

To json format same as :

[["1-12VEXP"],["1-124DH9"]]

in .net.

I'm using Newtonsoft.Json .

Any help will be greatly appreciated.


Straight-up serialization won't work, since the items are not equivalent. If you truly want what you're asking for, then you need an array which contains arrays, then serialize that array:

You can do that by first converting your collection, then simple JSON serialization:

string[][] newKeys = keys.Select(x => new string[]{x}).ToArray();

string json = JsonConvert.SerializeObject(newKeys);