Ricky
Ricky

Reputation: 35983

How divide a string into array

If I have the following plain string, how do I divide it into an array of three elements?

{["a","English"],["b","US"],["c","Chinese"]}

["a","English"],["b","US"],["c","Chinese"]

This problem is related to JSON string parsing, so I wonder if there is any API to facilitate the conversion.

Upvotes: 3

Views: 346

Answers (5)

Michael
Michael

Reputation: 20069

using String.Split won't work on a single token as the string in each token also contain a string (if I understood the requirements, the array elements should end up being:

  1. ["a","English"]
  2. ["b","US"]
  3. ["c","Chinese"]

If you use string.Split and use a comma as the delimiter the array will be made up of:

  1. ["a"
  2. "English"]
  3. ["b"
  4. "US"]
  5. ["c"
  6. "Chinese"]

A JSON parser that I've read about but never used is available here:

http://james.newtonking.com/pages/json-net.aspx

Upvotes: 0

Ian Mercer
Ian Mercer

Reputation: 39307

use DataContract serialization http://msdn.microsoft.com/en-us/library/bb412179.aspx

Upvotes: 2

Dan Diplo
Dan Diplo

Reputation: 25369

ASP.NET MVC comes with methods for easily converting collections to JSON format. There is also the JavaScriptSerializer Class in System.Web.Script.Serialization. Lastly there is also a good 3rd party library by James Newton called Json.NET that you can use.

Upvotes: 1

rerun
rerun

Reputation: 25505

I wrote a little console example using regex there is most likely a better way to do it.

static void Main(string[] args)
    {
        string str = "{[\"a\",\"English\"],[\"b\",\"US\"],[\"c\",\"Chinese\"]}";
        foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(str, @"((\[.*?\]))"))
        {
            Console.WriteLine(m.Captures[0]);
        }
    }

Upvotes: 1

Timores
Timores

Reputation: 14599

Remove the curly braces then use String.Split, with ',' as the separator.

Unfortunately, I never did JSON stuff so don't know a parsing library. Can't you let WCF do this stuff for you ?

Upvotes: 0

Related Questions