2011-07-19 61 views
2

我有这样的JSON:JSON解析,并检查使用SBJSON

{ 
    "errors": [ 
    ], 
    "warnings": [ 
    ], 
    "data": { 
     "token": "someToken" 
    }, 
    "page": { 
     "current": 1, 
     "total": 1 
    } 
} 

我试图解析与SBJSON令牌。解析它没有问题。但是,在某些情况下,检索到的JSON没有标记值。如何检查值是否存在,因为如果我不检查我的应用程序与EXCBadAccess崩溃。

谢谢!

+0

请让我知道,如果有什么我可以澄清我的答案:) – RedBlueThing

回答

2

SBJSON会给你一个NSDictionary对象。你只需要检查objectForKey返回的指针是否为零,并检查它是否为NSNull(如果值存在,将会是这种情况,但在JSON中设置为null),并且还可以确保数据是实际的一的NSDictionary:

id dataDictionaryId = [resultsDictionary objectForKey:@"data"]; 

// check that it isn't null ... this will be the case if the 
// data key value pair is not present in the JSON 
if (!dataDictionaryId) 
{ 
    // no data .. do something else 
    return; 
} 

// then you need to check for the case where the data key is in the JSON 
// but set to null. This will return you a valid NSNull object. You just need 
// ask the id that you got back what class it is and compare it to NSNull 
if ([dataDictionaryId isKindOfClass:[NSNull class]]) 
{ 
    // no data .. do something else 
    return; 
} 

// you can even check to make sure it is actually a dictionary 
if (![dataDictionaryId isKindOfClass:[NSDictionary class]]) 
{ 
    // you got a data thing, but it isn't a dictionary? 
    return; 
} 

// yay ... it is a dictionary 
NSDictionary * dataDictionary = (NSDictionary*)dataDictionaryId; 

// similarly here you could check to make sure that the token exists, is not null 
// and is actually a NSString ... but for this snippet, lets assume it is 
NSString * token = [dataDictionary objectForKey:@"token"]; 
if (!token) 
    // no token ... do something else 

更新

这是测试代码,我写检查SBJSON分析结果:

NSError* error = NULL; 
id json = [parser objectWithString:@"{\"data\":null}" error:&error]; 
NSDictionary * results = (NSDictionary*)json; 
id dataDictionaryId = [results objectForKey:@"data"]; 
if (!dataDictionaryId || [dataDictionaryId isKindOfClass:[NSNull class]]) 
    return NO; 
+0

谢谢,但应用程序仍然崩溃。如果我得到一个令牌回它的罚款,但如果我不它仍然崩溃。这是我没有令牌时返回的JSON:http://pastie.org/2234627 – Sunil

+0

@Sunil我会试试看,并回复你:) – RedBlueThing

+0

@Sunil试了一下,发现你得到一个有效的NSNull对象返回“数据”:null的情况。所以你只需要检查一下。 – RedBlueThing

0

尝试打印里面有什么数据字典时,有没有令牌。
Peraphs它不是零。
你可以检查isKindOfClass(NSDictionary),而不是放在!dataDictionary。