我正在尝试将一个JSON对象数组解析为C#中的字符串数组。我可以从JSON对象中提取数组,但我无法将数组字符串拆分为单个对象数组。这是我的测试字符串:
string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
目前我正在使用以下正则表达式将项目拆分为单独的对象。 现在它们是两个单独的正则表达式,直到我解决第二个正则表达式的问题:
Regex arrayFinder = new Regex(@"\{items:\[(?<items>[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?<items>\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
arrayFinder
正则表达式按照我预期的方式工作,但是出于我不理解的原因,arrayParser
正则表达式根本不起作用。我想要的只是将单个项拆分为它们自己的字符串,以便我得到像这样的列表:{id:0,name:"Lorem Ipsum"}
{id:1,name:"Lorem Ipsum"}
{id:2,name:"Lorem Ipsum"}
。无论这个列表是一个string[]
数组还是一个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:\[(?<items>[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?<items>\{[^\}]\}),?)+"
, 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;
有人能看出我哪里做错了吗?我完全卡住了。