我正在尝试解析JSON文件,因此我可以将其内容用作NSStrings
并在整个应用程序中显示在UILabels
中。
我的JSON:
{
"CustomText": [
{
"bodyText": "This is the body text",
"loginText": "This is the loginText",
"extraText": "This is the extra text"
}
]
}
我的代码:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];
NSArray *customStrings = json[@"CustomText"];
NSString *body = [customStrings valueForKey:@"bodyText"];
NSString *login = [customStrings valueForKey:@"loginText"];
self.labelText.text = body;
我不确定它为什么会中断,我看起来很惊讶并没有太多关于如何最好地使用本地JSON
文件。任何帮助都会很棒。
错误讯息:
由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:' - [__ NSArrayI length]: 无法识别的选择器发送到实例0x7f8080781740'
答案 0 :(得分:0)
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];
NSArray *customStrings = json[@"CustomText"];
NSString *body = [[customStrings objectAtIndex:0] valueForKey:@"bodyText"];
NSString *login = [[customStrings objectAtIndex:0] valueForKey:@"loginText"];
self.labelText.text = body;
答案 1 :(得分:0)
使用keypath
NSString * body = [json valueForKeyPath:@"CustomText.bodyText"];
self.labelText.text = body;