gpt4 book ai didi

iphone - 使用 SBJSON 进行 JSON 解析和检查

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:26:06 25 4
gpt4 key购买 nike

我有这个 JSON:

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

我正在尝试使用 SBJSON 解析 token 。解析没有问题。但是,在某些情况下,检索到的 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;

关于iphone - 使用 SBJSON 进行 JSON 解析和检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6741036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com