我想解析一个本地 json,我正试图这样做,但是 testDict
是 nil。谁能帮帮我吗?
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.searchResult removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", searchText];
NSString * firstLetter = [searchText substringWithRange:[searchText rangeOfComposedCharacterSequenceAtIndex:0]];
NSError *err = nil;
NSString *aux=@"english_";
NSString *updated = [aux stringByAppendingString:firstLetter];
NSString *dataPath = [[NSBundle mainBundle] pathForResource:updated ofType:@"json"];
testDict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&err];
Json 看起来像这样:
"Caaba": "(n.) The small and nearly cubical stone building, toward which all Mohammedans must pray.",
"Caas": "(n. sing. & pl.) Case.",
"Cab": [
"(n.) A kind of close carriage with two or four wheels, usually a public vehicle.",
"(n.) The covered part of a locomotive, in which the engineer has his station.",
"(n.) A Hebrew dry measure, containing a little over two (2.37) pints."
],
我正在检查是否是一个验证 json
最佳答案
我使用了以下代码:
NSString *path = @"/Users/JohnApple/Desktop/myJsonFileForThisTest.json";
NSError *err;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:kNilOptions error:&err];
NSLog(@"Here is the NSDicitonary if this worked --> %@",dict);
NSLog(@"Here is the NSError if it failed --> %@", err);
当我使用你上面提供的Json数据时:
"Caaba": "(n.) The small and nearly cubical stone building, toward which all Mohammedans must pray.",
"Caas": "(n. sing. & pl.) Case.",
"Cab": [
"(n.) A kind of close carriage with two or four wheels, usually a public vehicle.",
"(n.) The covered part of a locomotive, in which the engineer has his station.",
"(n.) A Hebrew dry measure, containing a little over two (2.37) pints."
],
我遇到了这个错误:
无法读取数据,因为它的格式不正确。”(JSON 文本未以数组或对象开头,并且未设置允许片段的选项
事实证明您的 JSON 格式不正确。要修复您的 Json,请在文件中的 json 开头添加一个 {
,并在最后添加一个 }
。
您可以通过检查 this site 来检查您的 JSON 格式是否正确。 .如果您的数据无效,您的 NSDIctionary 将为空。
将您的 Json 设置为正确的格式后,将正确显示以下数据:
{
Caaba = "(n.) The small and nearly cubical stone building, toward which all Mohammedans must pray.";
Caas = "(n. sing. & pl.) Case.";
Cab = (
"(n.) A kind of close carriage with two or four wheels, usually a public vehicle.",
"(n.) The covered part of a locomotive, in which the engineer has his station.",
"(n.) A Hebrew dry measure, containing a little over two (2.37) pints."
);
}
关于ios - NSDictionary 为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29742283/