-2

我有一个字符串:

[{"id":1,"gameName":"arizona","cost":"0.5E1","email":"hi@gmail.com","re​​quests":0},{"id":2 ,"gameName":"arizona","cost":"0.5E1","email":"hi@gmail.com","re​​quests":0},{"id":3,"gameName":"arizona ","cost":"0.5E1","email":"hi@gmail.com","re​​quests":0}]

但是,我想将此字符串解析为一个数组,例如:

[{"id":1,"gameName":"arizona","cost":"0.5E1","email":"hi@gmail.com","re​​quests":0}, {"id":2 ,"gameName":"arizona","cost":"0.5E1","email":"hi@gmail.com","re​​quests":0}, {"id":3,"gameName":"arizona ","cost":"0.5E1","email":"hi@gmail.com","re​​quests":0}]

该数组由大括号之间的逗号分隔:},{

我很喜欢使用命令

NSArray *responseArray = [response componentsSeparatedByString:@","];

但这会将字符串分隔为每个逗号处的值,这是不可取的。

然后我尝试使用正则表达式:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{.*\\}" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:response options:0 range:NSMakeRange(0, [response length])];

找到一个匹配项:从第一个花括号开始到最后一个花括号。我想知道是否有人新如何有效地解决这个问题?

4

2 回答 2

3

这个字符串似乎是有效的 JSON。尝试 JSON 解析器:NSJSONSerialization

于 2012-09-06T05:15:01.800 回答
0

I agree with H2CO3's suggestion to use a parser where possible.

But looking at your attempted regex, it looks like you just need to make it non-greedy, i.e.

@"\\{.*?\\}"
       ^
       |
       Add this question mark for non-greedy matching.

Of course, this will fail if you have deeper levels of (what I assume to be) nested arrays. Go with the JSON parser!

于 2012-09-06T05:22:01.250 回答