2013-04-26 29 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