9

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.

10
  • 1
    What have you already tried? Which JSON serializer are you using? (If you're not using anything yet, you should really pick one...)
    – Jon Skeet
    Jul 25, 2013 at 18:09
  • That's not JSON, and all you need is JSON.NET. Jul 25, 2013 at 18:10
  • @JonSkeet Newtonsoft.Json Jul 25, 2013 at 18:11
  • 1
    Note what you're asking for - those two are not the same thing. Your C# object is a collection of two strings. Your JSON object is an array which contains two arrays, each of which contains one item. Which do you want?
    – Joe Enos
    Jul 25, 2013 at 19:09
  • 2
    Serialization should never involve string manipulation - that's the whole point of it, not having to handle the formatting yourself. So I would not recommend @newStackExchangeInstance's approach (which isn't right anyway).
    – Joe Enos
    Jul 25, 2013 at 19:11

2 Answers 2

17

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);
2
  • I am using it in WebMethod. But it is showing 'the name ' json object ' does not exist in the current context'. ?? What's the problem here? Jan 7, 2014 at 10:42
  • @ShyamDixit Sounds like you've got a separate unrelated problem and should post that as a new question.
    – Joe Enos
    Jan 7, 2014 at 14:59
0

With Newtonsoft.Json:

JsonConvert.SerializeObject(keys);

will give you JSON.

1
  • 3
    Unfortunately, this will give you something like [&quot;1-12VEXP&quot;,&quot;1-124DH9&quot;] if for type IList<string>, which likely isn't usable; this would work if he were using type IList of a custom type w/ properties, for example.
    – Joe
    May 27, 2015 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.