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"开发者_C百科],["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.
use DataContract serialization http://msdn.microsoft.com/en-us/library/bb412179.aspx
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]);
}
}
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.
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 ?
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:
- ["a","English"]
- ["b","US"]
- ["c","Chinese"]
If you use string.Split and use a comma as the delimiter the array will be made up of:
- ["a"
- "English"]
- ["b"
- "US"]
- ["c"
- "Chinese"]
A JSON parser that I've read about but never used is available here:
http://james.newtonking.com/pages/json-net.aspx
精彩评论