【发布时间】:2010-09-29 08:15:15
【问题描述】:
我正在尝试将 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:\[(?<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;
谁能看出我做错了什么?我完全坚持这一点。
【问题讨论】:
-
json.org 上列出了几个用于 C#/.NET 的 JSON 解析器。为什么不使用其中之一?还是在挑战自己?
-
部分是为了挑战自己,部分是因为这是一小段代码,我觉得在这种情况下使用第三方库有点矫枉过正。
-
你如何衡量“矫枉过正”?如果您可以使用编写好的、经过测试的、可工作的代码,为什么不呢?
-
@Andy 在一个少于 100 行代码的项目中,如果没有必要,感觉应该避免需要外部 DLL。另外,就像我提到的那样,我也想要一些东西来挑战自己。
-
我建议,与其凭感觉使用外部库,不如看看自己编写它与使用经过测试的工作代码的成本和风险。