2011-07-19 94 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。