gpt4 book ai didi

ios - 使用 NSJSONSerialization 解析具有多个数组的 JSON 字典不会导致 NSDictionary 或 NSArray

转载 作者:行者123 更新时间:2023-11-28 19:05:09 25 4
gpt4 key购买 nike

我正在尝试以以下形式解析 JSON 字典:

{
"bible": {
"book": [
{
"bookName": "Genesis",
"chapter": [
{
"chapterNum": "1",
"verse": [
{
"verse": "In the beginning God created the heaven and the earth.",
"verseNum": "1"
},
{
"verse": "And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.",
"verseNum": "2"
},

我在获取此结构中的正确数据时遇到困难。我的目标是创建一个 Verse 托管对象,该对象具有 verseNum、verse(文本)、chapterNum 和 bookName 属性。

我需要帮助创建对象。目前,当我使用 NSJSONSerialization 创建 NSDictionary 时,我只获得了一个字典,只有一个 NSCFString:

    NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"kjv"
ofType:@"json"];

NSDictionary *bible = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];

for (NSDictionary *book in [bible valueForKey:@"bible"]) {
NSLog(@"%@", book);
}

控制台输出只是:book

最佳答案

试试下面的代码:

NSError *error = nil;
id JSONResponse = [NSJSONSerialization JSONObjectWithData:self.responseData
options:0
error:&error];

if (error) {
NSLog(@"JSON Error: %@", error);
return;
}

// Should be an NSDictionary or NSArray
NSLog(@"JSON response: %@", [JSONResponse description]);

NSArray *books = [JSONResponse valueForKeyPath:@"bible.book"];

for (NSDictionary *book in books) {
NSLog(@"%@", book);
NSString *bookName = [book valueForKey:@"bookName"];
NSArray *chapters = [book valueForKey:@"chapter"];
// loop through the chapters
...
NSArray *verses = [book valueForKey:@"verse"];
// loop through the verses
...
}

关于ios - 使用 NSJSONSerialization 解析具有多个数组的 JSON 字典不会导致 NSDictionary 或 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105592/

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