【问题标题】:SBJSON parsing NSString to NSDictionarySBJSON 将 NSString 解析为 NSDictionary
【发布时间】:2012-02-23 19:46:53
【问题描述】:

我正在尝试使用 SBJson 3.0.4 将包含 JSON 数据的 NSString 解析为 NSDictionary,但是当我这样做时,我收到此错误:

“WebKit 在 webView 中丢弃了一个未捕获的异常:shouldInsertText:replacingDOMRange:givenAction: delegate: -[__NSCFString JSONValue]: unrecognized selector sent to instance 0x6ab7a40”

据我所知(不是很远),我得到的 JSON 是有效的,所以我不知道为什么会这样。我的代码也编译得很好…… 这里是:

NSString *tempURL = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true",userInput.text];
NSURL *url = [NSURL URLWithString:tempURL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url 
                                            cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                        timeoutInterval:30];
// fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;

// make the synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest 
                                returningResponse:&response 
                                            error:&error];

// construct a String around the Data from the response
NSString *data = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *feed = [data JSONValue];

【问题讨论】:

  • 打印字符串data的值。将数据内容复制到 JSONLint.com 上的工具中,看看它是否是有效的 JSON。让我们知道会发生什么。

标签: objective-c json nsstring nsdictionary sbjson


【解决方案1】:

错误信息的重要部分是这样的:

-[__NSCFString JSONValue]: unrecognized selector sent to instance 0x6ab7a40

__NSCFString 类是NSString 接口的私有实现类,所以你可以假装它是NSString

所以我们看到您将JSONValue 消息发送到NSString,而NSString 表示它无法识别该选择器。 SBJson 库在NSStringusing a category 中添加了一个JSONValue 方法。

所以我推断您没有将NSObject+SBJson.o 链接到您的应用程序中。如果您将 SBJson 源文件复制到您的应用中,请确保您复制到 NSObject+SBJson.m,并确保它包含在目标的“编译源”构建阶段。

如果您构建了一个 SBJson 库并将您的应用链接到该库,您可能需要将 -ObjC 标志添加到您的链接器选项,甚至是 -all_load 标志。

【讨论】:

  • 我忘记将它添加到编译源中,但是当我这样做时,我现在得到了两个错误:Undefined symbols for architecture i386: "_OBJC_CLASS_$_SBJsonWriter", referenced from: objc-class-ref in NSObject+SBJson.o "_OBJC_CLASS_$_SBJsonParser", referenced from: objc-class-ref in NSObject+SBJson.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)
  • 您需要将所有的 SBJson .m 文件添加到“编译源”构建阶段。
  • 谢谢!你节省了我很多时间
猜你喜欢
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多