JSON string from NSDictionary having file path
11,970
The path separators shouldn't be a problem when converting your dictionary to a JSON string.
Your sample doesn't show the type & initialization of your json
variable but you can obtain a JSON representation from your dict the following way:
NSDictionary* jsonDict = @{ @"background": @"file://localhost/var/mobile/Applications/6118A03F-345B-42D5-AC19-25F6D9AC4484/Documents/background.caf",
@"bgMusic": @"file://localhost/var/mobile/Applications/6118A03F-345B-42D5-AC19-25F6D9AC4484/Documents/bgMusic.caf"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:nil];
NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(@"Dict:%@", jsonString);
This works fine here (including proper escaping for the path separators in the log line)
Author by
user7388
Updated on June 26, 2022Comments
-
user7388 almost 2 years
I am working on the app in which I store the file name and file path in NSDictionary. My dictionary like,
Dict Path : { background = "file://localhost/var/mobile/Applications/6118A03F-345B-42D5-AC19-25F6D9AC4484/Documents/background.caf"; bgMusic = "file://localhost/var/mobile/Applications/6118A03F-345B-42D5-AC19-25F6D9AC4484/Documents/bgMusic.caf"; }
It's works fine, but when I tried to convert the dictionary in JSON string,
NSString *strPathForSong = [json stringWithObject:dictPath]; NSLog(@"path sting : %@",strPathForSong);
it returns null string. So is there any way to convert dictionary having "/" string into json string?? Thank you in advance
-
user7388 about 11 yearsit works fine with your given jsonDict, but when I replace the name of dicationary for NSData, it gets crash, and gives error "reason: 'Invalid type in JSON write (NSURL)'".
-
Thomas Zoechling about 11 yearsIt seems your paths are stored as NSURL objects in the dictionary. Convert them to strings first with [NSURLobject absoluteString].