ios - AFNetworking GET 请求 - 无法将 responseObject 转换为 NSDictionary
<p><p>我尝试了几个将 <code>responseSerializer</code> 设置为 <code>JSON</code> 的选项,但我无法将 responseObject 转换为 <code>NSDictionary</code>。问题是我得到的响应是 <code>NSData</code></p>
<pre><code> NSString *baseURLString = @"Your URL?";
NSString *str = @"adult=false&gender=male";
NSString *url = ;
AFHTTPRequestOperationManager *manager = ;
manager.responseSerializer = ;
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, idresponseObject) {
// do whatever you'd like here; for example, if you want to convert
// it to a string and log it, you might do something like:
NSLog(@"responseObject %@",responseObject);
NSString *jsonString = [ initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseObject
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"json %@",json);
if (error) {
NSLog(@"%@",);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
</code></pre>
<p>这个 <code>NSLog(@"%@",);</code> 给出的错误如下:</p>
<pre><code>Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed.
(Cocoa error 3840.)" (Garbage at end.)
UserInfo=0xa7c5440 {NSDebugDescription=Garbage at end.}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您的 JSON 最后返回垃圾。 </p>
<p> <img src="/image/QhSIQ.jpg" alt="enter image description here"/>
您应该修复您的 web 服务,使其不在 JSON 末尾嵌入时间戳和语言。如果您无法更改您的网络服务,请使用以下方法从您的 json 中删除尾随垃圾,然后再次使用 <code>NSJSONSerialization</code> 解析它。</p>
<pre><code>NSRange range = ;
jsonString = ;
</code></pre>
<p>然后将这个清理后的 <code>jsonString</code> 解析为 <code>NSDictionary</code>:</p>
<pre><code>NSData *newJSONData = ;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:newJSONData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"json %@",json);
</code></pre>
<p>它应该可以正常工作。</p></p>
<p style="font-size: 20px;">关于ios - AFNetworking GET 请求 - 无法将 responseObject 转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/22370420/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/22370420/
</a>
</p>
页:
[1]