Sachin Prasad
Sachin Prasad

Reputation: 5411

Convert a list of string into json format

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.

Upvotes: 9

Views: 72415

Answers (2)

Joe Enos
Joe Enos

Reputation: 40393

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

Upvotes: 17

user47589
user47589

Reputation:

With Newtonsoft.Json:

JsonConvert.SerializeObject(keys);

will give you JSON.

Upvotes: 0

Related Questions