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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

With Newtonsoft.Json:

JsonConvert.SerializeObject(keys);

will give you JSON.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x