4
NSLog(@"%@", request.responseString);

这给了我的输出{"errors":{"email":["is already taken"]}}

我想将电子邮件和消息字符串保存"is already taken"为字符串以显示在警报中。如何将这两个项目访问到两个字符串中?

4

4 回答 4

4

响应字符串是服务器的原始输出。在这种情况下,它是 JSON 编码的。您可以使用 AFNetworking JSON 特定类之一(即AFJSONRequestOperation)将响应作为 JSON 对象返回,或者使用NSJSONSerialization. 我建议使用AFJSONRequestOperation.

于 2013-07-19T09:46:37.897 回答
1
 NSData *data = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];

 id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
 NSString *str = [[json objectForkey:@"errors"] objectForKey:@"email"][0];
于 2013-07-19T09:48:30.287 回答
0

我使用了以下,似乎更强大一点:

[requestOperation setCompletionBlockWithSuccess:success failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id response = error.userInfo;
    if (response && [response isKindOfClass:[NSDictionary class]]) {
        NSDictionary *responseDictionary = (NSDictionary *)response;

        // AFNetworking hides the actual error response under this key 
        if ([responseDictionary valueForKey:NSLocalizedRecoverySuggestionErrorKey]) {
            id suggestedRecovery = [responseDictionary valueForKey:NSLocalizedRecoverySuggestionErrorKey];

            if ([suggestedRecovery isKindOfClass:[NSString class]]) {
                // Try to json decode string
                id json = [NSJSONSerialization JSONObjectWithData:[suggestedRecovery dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                if (json && [json isKindOfClass:[NSDictionary class]]) {
                    responseDictionary = json;
                }
            }
        }

        // .. extract error message out of responseDictionary
    }
    }];
于 2013-10-23T02:24:44.360 回答
-1
    NSData *responseData = [[error userInfo] objectForKey:@"data"];
    if ([responseData length] > 0)
    {

     NSString *str = [[NSString alloc] initWithData:responseData                                                                                encoding:NSUTF8StringEncoding];
      NSLog(@"%@", str);
    }
于 2013-07-19T10:57:08.577 回答