tags:

views:

137

answers:

5

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.

A: 

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 ?

Timores
+1  A: 

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]);
        }
    }
rerun
@rerun: I saw ur solution most suiting my current situation. Could elaborate more on the match pattern? I'm not aware of Regex. Thx.
Ricky
Regex is a big topic but basicly its a way of shorthand text matching and capturing. the match string I provided match all characters between [] and stores them in a capture. take a look at http://www.regular-expressions.info/tutorial.html it has a ton of great info.
rerun
Thx. What's the double parentheses means?
Ricky
You'll need a better regex than that if your strings ever contain '[' or ']' characters. Or as Jamie Zawinski put it in his famous quote from 1997 "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." DataContract serialization is a better bet.
Hightechrider
+1  A: 

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.

Dan Diplo
+1  A: 

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

Hightechrider
A: 

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

Michael Shimmins