我只想使用SBJSON框架解析Objective-C中的这个JSON字符串,并检索三个数据单元:
{"x":"197","y":"191","text":"this is a string"}
如何做到这一点?
答案 0 :(得分:4)
NSString * jsonString = @"{\"x\":\"197\",\"y\":\"191\",\"text\":\"this is a string\"}";
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:jsonString];
NSLog(@"x is %@",[dictionary objectForKey:@"x"]);
[jsonParser release];
答案 1 :(得分:2)
以下是一个例子:
NSString *jsonText = @"...";
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *dict = [parser objectWithString:jsonText];
for (NSString *key in [@"x y text" componentsSeparatedByString:@" "]) {
NSLog(@"%@ => %@", key, [dict objectForKey]);
}
这与SBJson4Parser类似:
id parser = [SBJson4Parser parserWithBlock:^(id v, BOOL *stop) {
for (NSString *key in [@"x y text" componentsSeparatedByString:@" "]) {
NSLog(@"%@ => %@", key, [v objectForKey]);
}
}
allowMultiRoot:NO
unwrapRootArray:NO
errorHandler:^(NSError *err) {
// handle error here
}];
NSString *jsonText = @"...";
[parser parse: [jsonText UTF8String]];