Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用SBJSON在Objective-C中解析JSON_Objective C_Json - Fatal编程技术网

使用SBJSON在Objective-C中解析JSON

使用SBJSON在Objective-C中解析JSON,objective-c,json,Objective C,Json,我只想使用SBJSON框架在Objective-C中解析这个JSON字符串,并检索三个数据单元: {"x":"197","y":"191","text":"this is a string"} 如何做到这一点?以下是一个示例: NSString * jsonString = @"{\"x\":\"197\",\"y\":\"191\",\"text\":\"this is a string\"}"; SBJSON *jsonParser = [[SBJSON alloc] init]; NSD

我只想使用SBJSON框架在Objective-C中解析这个JSON字符串,并检索三个数据单元:

{"x":"197","y":"191","text":"this is a string"}
如何做到这一点?

以下是一个示例:

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];
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]];

还请注意,[dictionary objectForKey:@“x”]将返回一个NSNumber,而不是整数,因此使用%@格式说明符。
[dictionary objectForKey:@“x”]
将实际返回一个
NSString
,因为该值在原始JSON数据中引用。这是一个真正古老的SBJson版本。请不要再使用它了!哈,那就是奉献!请随时更新或包含指向新示例或文档的链接。使用SBJson4Parser可以进行这种简单的解析吗?@ReneDohan是的,尽管您的代码会有很大的不同。如果您想解析在本地机器上已经有权访问的小JSON字符串,您可能只需要使用NSJSONSerialization。如果您需要/想要异步解析,请访问SBJson4Parser。但我还需要-(id)proxyForJson的功能,这是我现在真正使用的,在其他库中看不到的。谢谢你。@ReneDohan这很有道理,所以我添加了一个例子。正如你所看到的,SBJson 4并不是最适合的:-)所以我现在将继续使用3.1.1版本,因为我认为没有简单的json库可以通过简单的语法实现sbjson3的功能,我希望解析器能够输出字典,正如我所看到的,我可以在该块中创建字典,但对开发人员来说似乎不友好,proxyForJson功能对我来说非常方便,我可以创建复杂的对象数据层次结构并将它们转换回json。。。对我来说,这是最好的功能和简单的解析