使用SBJSON解析和检查



我有这个JSON:

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

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

谢谢!

SBJSON将返回给你一个NSDictionary对象。你只需要检查objectForKey返回的指针是否为nil,也检查它是否为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;

尝试在没有标记的情况下打印出dataDictionary内部的内容。
也许它不是nil。
你可以检查isKindOfClass(NSDictionary),而不是直接放!dataDictionary.

最新更新