Objective c Cocoa Touch-如何解析本地Json文件

Objective c Cocoa Touch-如何解析本地Json文件,objective-c,ios,json,cocoa-touch,Objective C,Ios,Json,Cocoa Touch,我是iOS开发的新手,我正在尝试解析一个本地Json文件,比如 {“quizz”:[{“id”:“1”,“Q1”:“米奇出生时”,“R1”:“1920”,“R2”:“1965”,“R3”:“1923”,“R4”,“1234”,“response”,“1920”},{“id”:“1”,“Q1”:“冷战何时开始”,“R1”:“1920”,“R2”:“1965”,“R3”:“1923”,“rep4”,“1234”,“response”,“1920”} 这是我的密码: NSString *filePa

我是iOS开发的新手,我正在尝试解析一个本地Json文件,比如

{“quizz”:[{“id”:“1”,“Q1”:“米奇出生时”,“R1”:“1920”,“R2”:“1965”,“R3”:“1923”,“R4”,“1234”,“response”,“1920”},{“id”:“1”,“Q1”:“冷战何时开始”,“R1”:“1920”,“R2”:“1965”,“R3”:“1923”,“rep4”,“1234”,“response”,“1920”}

这是我的密码:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
// Parse the string into JSON
NSDictionary *json = [myJSON JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"quizz"];

NSEnumerator *enumerator = [items objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}
我在这个网站上找到了一个样本,但我发现了以下错误


-JSONValue失败。错误是:对象键后不应出现标记“值分隔符”。

JSON具有严格的键/值表示法,R4和响应的键/值对不正确。试试这个:

NSString *jsonString = @"{\"quizz\":[{\"id\":\"1\",\"Q1\":\"When Mickey was born\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"response\":\"1920\"}]}";
如果从文件中读取字符串,则不需要所有斜杠
您的文件如下所示:

{“测验”:[{“id”:“1”,“Q1”:“米奇出生时” 出生,R1:“1920”,“R2:“1965”,“R3:“1923”,“R4:“1234”,“回复:”“1920”},{“id:”“1”,“Q1:”“何时?” 感冒 战争、R1:“1920”、“R2:“1965”、“R3:“1923”、“R4:“1234”、“回复:“1920”}


我使用以下代码进行了测试:

NSString *jsonString = @"{\"quizz\":[{\"id\":\"1\",\"Q1\":\"When Mickey was born\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"response\":\"1920\"}, {\"id\":\"1\",\"Q1\":\"When start the cold war\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"reponse\":\"1920\"}]}";
NSLog(@"%@", jsonString);
NSError *error =  nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];

NSArray *items = [json valueForKeyPath:@"quizz"];

NSEnumerator *enumerator = [items objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}
我得到的印象是,您复制了旧代码,因为您没有使用apple的序列化和枚举器而不是。整个枚举的内容可以简单地写成

NSArray *items = [json valueForKeyPath:@"quizz"];
for (NSDictionary *item in items) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}
或者,如果需要快速安全的枚举,您还可以添加索引

NSArray *items = [json valueForKeyPath:@"quizz"];
[items enumerateObjectsUsingBlock:^(NSDictionary *item , NSUInteger idx, BOOL *stop) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}];

您的json文件中似乎有输入错误

替换
“R4”、“1234”、“响应”、“1920”和
“R4”:“1234”、“响应”:“1920”


“rep4”、“1234”、“response”、“1920”和
“rep4”:“1234”、“response”:“1920”
用于查找JSON字符串中的错误。
在本例中,它表示在“R4”附近有无效的JSON 我使用实用程序方法将JSON文件转换为字典:

func getDictionaryFromJSON(jsonFileName: String) -> [String: AnyObject]? {
    guard let filepath = NSBundle.mainBundle().pathForResource(jsonFileName, ofType: "json") else {
        return nil
    }

    guard let data = NSData(contentsOfFile: filepath) else {
        return nil
    }

    do {
        let dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
        return dict
    } catch {
        print(error)
        return nil
    }
}

非常感谢你的帮助。还有一个问题,如何检索数组中的特定对象索引并浏览键值?我的意思是,如果我想直接选择第二个对象并显示id值,那么一旦解析了json字符串,就会有nsarray和dictionary。因此,对于数组,您可以执行
item=[items objectAtIndex:1]
来获取第二个项。但这与json无关。这是标准的数组/字典内容。
func getDictionaryFromJSON(jsonFileName: String) -> [String: AnyObject]? {
    guard let filepath = NSBundle.mainBundle().pathForResource(jsonFileName, ofType: "json") else {
        return nil
    }

    guard let data = NSData(contentsOfFile: filepath) else {
        return nil
    }

    do {
        let dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
        return dict
    } catch {
        print(error)
        return nil
    }
}