2012-10-03 47 views
1

我一直在抨击我的头撞墙。iOS解析JSON困境

我有一个将JSON返回给我的iOS应用程序的rails后端。我使用rails的默认返回值来自动呈现JSON中的对象。我遇到了它返回的错误。

我得到的JSON错误是{"errors":{"email":["can't be blank"],"password":["can't be blank"]}}

我使用ASI来处理请求。

-(void) requestFinished:(ASIFormDataRequest *)request { 
    NSDictionary *data = [[request responseString] JSONValue]; 

做上面的代码使数据成为:

{ 
    errors =  
    { 
    email =   (
     "can't be blank" 
    ); 
    password =   (
     "can't be blank" 
    ); 
    }; 
} 

现在,这给了我的问题试图解析出来。我希望能够访问错误的每个元素及其相关的值。

当我通过元素尽量循环,我做这样的事情:

for (NSDictionary *error in [data objectForKey:@"errors"]) 

这会给我emailpassword,但他们是类型__NSCFString,不NSDictionary的。我一直无法找到获取电子邮件或密码价值的方法。有没有人有关于如何解析这个问题的想法?

谢谢!

回答

1

这应该工作,请注意,响应具有与您的'数据'NSDictionary相同的结构。

NSDictionary *fields = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSArray alloc] initWithObjects:@"one", @"two", nil], 
                   @"A", 
                   [[NSArray alloc] initWithObjects:@"three", @"four", nil], 
                   @"B", 
                   nil]; 

NSDictionary *response = [[NSDictionary alloc] initWithObjectsAndKeys:fields, @"errors", nil]; 

NSLog(@"Dictionary: %@", [response objectForKey:@"errors"]); 


for (NSString *field in [response objectForKey:@"errors"]) 
    for (NSString* error in [response valueForKeyPath:[NSString stringWithFormat:@"errors.%@", field]]) 
     NSLog(@"%@ %@", field, error); 

输出将是这样的:

Dictionary: { 
A =  (
    one, 
    two 
); 
B =  (
    three, 
    four 
); 
} 

A one 
A two 
B three 
B four 
1

那么我没有Mac现在,但我试图帮助你,如果它不工作让我知道我明天会纠正它。

-(void) requestFinished:(ASIFormDataRequest *)request 
{ 
    NSArray *data = [[request responseString] JSONValue]; 
    NSDictionary *dict = [data objectAtIndex:0]; 

    NSDictionary *dict2 = [dict valueForKey:@"errors"]; 

    NSLog(@"email = %@, password = %@",[dict2 valueForKey:@"email"], [dict2 valueForKey:@"password"]); 
} 
+0

感谢没有你的MAC得心应手尝试。不幸的是,它不会使用NSArray。接受的答案确实工作,看起来像valueForKeyPath是唯一的方法来做到这一点。 – LyricalPanda

+0

好的恭喜!我很高兴你的问题已经解决。 – TheTiger