2013-04-26 30 views
3

我正在处理在NSDictionary中存储文件名和文件路径的应用程序。我的字典一样,来自NSDictionary的具有文件路径的JSON字符串

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"; 
} 

它工作正常,但是当我试图转换的字典中JSON字符串,

NSString *strPathForSong = [json stringWithObject:dictPath]; 
     NSLog(@"path sting : %@",strPathForSong); 

返回空字符串。那么有没有办法将带有“/”字符串的字典转换为json字符串? 预先感谢您

+0

你能否提供你如何试图将NSDictionary转换为JSON的源代码? – 2013-04-26 06:10:05

+0

我已经在我的问题中提到过。请检查。 – user7388 2013-04-26 06:27:31

回答

10

将字典转换为JSON字符串时,路径分隔符不应成为问题。
您的样品不显示你json变量的&类型的初始化,但你可以从你的字典JSON表示方式如下:

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); 

在这里,这工作正常(包括正确转义路径分隔符日志行)

+1

它适用于你给定的jsonDict,但是当我替换NSData的dicationary名称时,它会崩溃,并给出错误“reason:'JSON写入(NSURL)'”中的无效类型。 – user7388 2013-04-26 06:26:45

+4

看来你的路径被存储为字典中的NSURL对象。先用[NSURLobject absoluteString]将它们转换为字符串。 – 2013-04-26 06:33:55

+0

哦...好的..让我试试 – user7388 2013-04-26 06:43:05