我是Json开发人员的新手,我正在尝试解析本地iOS文件,例如
{"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","rep4","1234","reponse","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失败。错误是:对象键后不应有标记“值分隔符”。
发布于 2016-08-18 16:16:33
Swift 2.3 JSON I使用实用程序方法将文件转换为字典:
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
}
}https://stackoverflow.com/questions/12150595
复制相似问题