Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of string into json format

Tags:

json

c#

asp.net

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.

like image 788
Sachin Prasad Avatar asked Jul 25 '13 18:07

Sachin Prasad


1 Answers

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);
like image 97
Joe Enos Avatar answered Oct 15 '22 07:10

Joe Enos