JSON使用SBJSON进行解析和检查

时间:2011-07-19 00:29:42

标签: iphone ios json

我有这个JSON:

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

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

谢谢!

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:0)

当没有令牌时,尝试打印出内部数据字典 佩拉夫不是零 您可以检查isKindOfClass(NSDictionary),而不仅仅是put!data Dictionary。