gpt4 book ai didi

ios - 使用NSDictionary进行JSON解析并按键查找值

转载 作者:行者123 更新时间:2023-12-01 18:28:17 24 4
gpt4 key购买 nike

我有一个简单的NSDictionary,试图通过返回的JSON使用来自外部站点的数据来填充。返回的JSON很好,但是我在获取特定键的实际数据时遇到麻烦。

这是打印到控制台的JSON数据。

这是我的JSON数据:

(
{
CategoryID = 12345;
CategoryName = "Baked Goods";
},
{
CategoryID = 12346;
CategoryName = Beverages;
},
{
CategoryID = 12347;
CategoryName = "Dried Goods";
},
{
CategoryID = 12348;
CategoryName = "Frozen Fruit & Vegetables";
},
{
CategoryID = 12349;
CategoryName = Fruit;
},
{
CategoryID = 12340;
CategoryName = "Purees & Soups";
},
{
CategoryID = 12341;
CategoryName = Salad;
},
{
CategoryID = 12342;
CategoryName = "Snack Items";
},
{
CategoryID = 12343;
CategoryName = Vegetables;
}
)

我得到的错误是:

由于未捕获的异常而终止应用程序
“NSInvalidArgumentException”,原因:“-[__ NSCFArray
enumerateKeysAndObjectsUsingBlock:]:无法识别的选择器发送到
实例0x6884000'
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

NSError *error = nil;
// Get the JSON data from the website
NSDictionary *categories = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

if (categories.count > 0){
NSLog(@"This is my JSON data %@", categories);

[categories enumerateKeysAndObjectsUsingBlock: ^(__strong id key, __strong id obj, BOOL *stop) {
NSLog(@"Key = %@, Object For Key = %@", key, obj); }];
}

我不确定为什么会这样,但是我确定这很简单,就像我使用了不正确的对象一样。

感谢帮助。

最佳答案

+JSONObjectWithData:options:error:返回的是NSArray,而不是NSDictionary。 '-[__NSCFArray enumerateKeysAndObjectsUsingBlock:]是错误消息的关键部分。它告诉您正在数组上调用-enumerateKeysAndObjectsUsingBlock:

对于这种情况,可以改用-enumerateObjectsUsingBlock:
如果不确定是否会返回NSArray或NSDictionary,则可以使用-isKindOf:

id result = [NSJSONSerialization …];
if ([result isKindOf:[NSArray class]]) {
NSArray *categories = result;
// Process the array
} else if ([result isKindOf:[NSDictionary class]]) {
NSDictionary *categories = result;
// Process the dictionary
}

enumerateObjectsUsingBlock:

使用数组中的每个对象执行给定的块,从第一个对象开始,一直到数组到最后一个对象。
  • (void)enumerateObjectsUsingBlock:(void(^)(id obj,NSUInteger idx,BOOL * stop))阻止

  • 所以应该这样称呼
    [categories enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"index = %d, Object For Key = %@", idx, obj);
    }];
    快速阅读文档确实可以为您省去很多麻烦。

    关于ios - 使用NSDictionary进行JSON解析并按键查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143146/

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