JSON string from NSDictionary having file path

user7388 picture user7388 · Apr 26, 2013 · Viewed 12k times · Source

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

Answer

Thomas Zoechling picture Thomas Zoechling · Apr 26, 2013

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)