我访问 RESTFUL 网址并返回结果。结果采用 JSON 格式。我通过以下方式将响应转换为字符串:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *json = [[NSString alloc] initWithBytes:[self.receivedData mutableBytes] length:[self.receivedData length] encoding:NSUTF8StringEncoding];
json 变量的值为 0x0。当我将鼠标悬停在其上时,我会看到 >。我如何调试它以了解其无效的原因?我在 JSON 解析器中渲染通过浏览器返回的 JSON。检查结果很好。
通过在 URL 中输入 ID 来返回结果。其他 ID 返回结果没有问题。结果集相当大。
I access a RESTFUL url and get back results. The results are in JSON. I turn the response into a string via:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *json = [[NSString alloc] initWithBytes:[self.receivedData mutableBytes] length:[self.receivedData length] encoding:NSUTF8StringEncoding];
The json variable has a value of 0x0. When I mouse over it, I see <Invalid CFStringRef
>. How can I debug this to tell why it is invalid? I render the JSON given back through the browser in A JSON parser. That checks out fine.
Results are given back by entering an ID in the URL. Other IDs return results without issue. The result set is fairly large.
发布评论
评论(2)
首先,我将使用 initWithData:encoding: 来设置 NSString。差别很小,但这种方法的存在是有原因的。
然后,我会对 self.receivedData 进行十六进制转储以查看其中实际内容。如果该数据未正确进行 UTF8 编码,则
initWithData:encoding:
将失败。(Google for NSData hex dump 来查找其他人的实用函数来执行此操作)
我发现有时 Web 服务的编码很马虎。所以我通常会实现这样的后备:
令人遗憾的是,这是必需的,但许多 Web 服务没有正确编写或配置。
First I would use
initWithData:encoding:
to setup the NSString. Small difference, but that method is there for a reason.Then, I would do a hexdump of
self.receivedData
to see what is actually in there. If that data is not properly UTF8 encoded then theinitWithData:encoding:
will fail.(Google for NSData hex dump to find other people's utility functions to do this)
I have found that sometimes web services are sloppy with their encoding. So I usually implement a fallback like this:
It is kind of sad that this is required but many web services are not written or configured properly.
使用 NSLog 查看字节。
Use
NSLog
to look at the bytes.