我正在尝试将JSON对象数组解析为C#中的字符串数组。我可以从JSON对象提取数组,但不能将数组字符串拆分为单个对象的数组。
我有这个测试字符串:
string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
现在,我现在正在使用以下正则表达式将项目拆分为单个对象。现在,它们是2个单独的正则表达式,直到我解决第二个正则表达式为止:
Regex arrayFinder = new Regex(@"\{items:\[(?[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
在arrayFinder正则表达式的工作,我期望它,但对于原因,我不明白的方式,arrayParser正则表达式不会在所有的工作。我要做的就是将各个项目拆分成自己的字符串,这样我就得到了一个列表:
{id:0,name:"Lorem Ipsum"}
{id:1,name:"Lorem Ipsum"}
{id:2,name:"Lorem Ipsum"}
这个列表是string[]数组还是a
Group或Match集合都没有关系,但是我对如何拆分对象感到困惑。使用上面声明的arrayParser和json字符串,我尝试了以下代码,我认为该代码可以正常使用:
string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
Regex arrayFinder = new Regex(@"\{items:\[(?[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
string array = arrayFinder.Match(json).Groups["items"].Value;
// At this point the 'array' variable contains:
// {id:0,name:"Lorem Ipsum"},{id:1,name:"Lorem Ipsum"},{id:2,name:"Lorem Ipsum"}
// I would have expected one of these 2 lines to return
// the array of matches I'm looking for
CaptureCollection c = arrayParser.Match(array).Captures;
GroupCollection g = arrayParser.Match(array).Groups;
有人可以看到我在做什么错吗?我完全被这个困扰。