iosobjective-cfilepathjsonreader

Can not read the specific values of json file in objective c


I have downloaded the json files in my App Folder and I want to read that files from my App Folder to print specific values.

Files are located like this : /var/mobile/Containers/Data/Application/63E66EE9-9A1B-4D4D-AEF6-F8C54D159ED0/Library/NoCloud/MyApp/MyFolder/DTS.json

This is what file contains: [{"value":0}] However the file contents are read and printed in console as I have mentioned below but when I read specific value it gives 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);

This shows This is Dts contents [{"value":0}] 2018-06-11 17:04:40.940006+0500 Muslims 365[3356:819935] here is DTS data (null)


Solution

  • The error occurs because you are getting an NSString from a file URL and then you are getting NSData from that string as file path which cannot work. Omit that step:

    NSURL *libraryDirURL = [[NSFileManager.defaultManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *urlDTSK = [libraryDirURL URLByAppendingPathComponent:@"NoCloud/MyApp/MyFolder/DTS.json"];
    NSData *dataDTS = [NSData dataWithContentsOfURL: urlDTSK];
    

    By the way the retrieved JSON is an array, you get the value for key Value from the first element which seems to be a numeric value (NSNumber).

    And handle the error!

    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