我已经在我的 App 文件夹中下载了 json 文件,我想从我的 App 文件夹中读取该文件以打印特定值。
文件位置如下:/var/mobile/Containers/Data/Application/63E66EE9-9A1B-4D4D-AEF6-F8C54D159ED0/Library/NoCloud/MyApp/MyFolder/DTS.json
/p>
这是文件包含的内容:[{"value":0}] 然而,正如我在下面提到的,文件内容是在控制台中读取和打印的,但是当我读取特定值时,它给出 null
NSURL *libraryDirURL = [[NSFileManager.defaultManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *urlDTSK = [libraryDirURL URLByAppendingPathComponent:@"NoCloud/MyApp/MyFolder/DTS.json"];
NSString *filePathDTS = [NSString stringWithContentsOfURL:urlDTSK encoding:NSUTF8StringEncoding error:nil];
NSLog(@"This is Dts PATH %@", filePathDTS);
NSData *dataDTS = [NSData dataWithContentsOfFile:filePathDTS];
NSLog(@"here is DTS data %@", dataDTS); //this shows null
NSDictionary *jsonDTS = [NSJSONSerialization JSONObjectWithData:dataDTS options:kNilOptions error:nil];
NSLog(@"here is jason DTS %@", jsonDTS);
NSMutableArray *DTSvalue = [jsonDTS valueForKeyPath: @"Value"];
DTSValueIs = DTSvalue[0];
NSLog(@"here is DTS Value first%@", DTSvalue[0]);
NSLog(@"here is DTS value is%@", DTSValueIs);
这显示 这是 Dts 内容 [{"value":0}]
2018-06-11 17:04:40.940006+0500 Muslims 365[3356:819935] 这里是DTS数据(null)
最佳答案
发生错误是因为您从文件 URL 获取 NSString
,然后从 that string 获取 NSData
作为文件路径不能工作。省略那一步:
NSURL *libraryDirURL = [[NSFileManager.defaultManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *urlDTSK = [libraryDirURL URLByAppendingPathComponent:@"NoCloud/MyApp/MyFolder/DTS.json"];
NSData *dataDTS = [NSData dataWithContentsOfURL: urlDTSK];
顺便说一句,检索到的 JSON 是一个数组,您可以从第一个似乎是数字值 (NSNumber
) 的元素中获取键 Value
的值。
并处理错误!
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:dataDTS options:kNilOptions error:&error];
if (error) { NSLog(@"%@", error); }
NSNumber *dtsValue = jsonArray[0][@"value"];
NSLog(@"here is DTS value: %@", dtsValue); // here is DTS value: 0
关于ios - 无法读取 objective-c 中json文件的具体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50795101/