3

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
  • 1,741
  • 2
  • 19
  • 25

1 Answers1

10

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)

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • 1
    it 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)'". – user7388 Apr 26 '13 at 06:26
  • 4
    It seems your paths are stored as NSURL objects in the dictionary. Convert them to strings first with [NSURLobject absoluteString]. – Thomas Zoechling Apr 26 '13 at 06:33