【问题标题】:JSON string from NSDictionary having file path来自 NSDictionary 的 JSON 字符串具有文件路径
【发布时间】:2013-04-26 06:01:49
【问题描述】:

我正在开发将文件名和文件路径存储在 NSDictionary 中的应用程序。我的字典喜欢,

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字符串? 提前谢谢你

【问题讨论】:

  • 您能否提供您如何尝试将 NSDictionary 转换为 JSON 的源代码?
  • 我已经在我的问题中提到了。请检查。

标签: ios objective-c parsing nsstring sbjson


【解决方案1】:

将您的字典转换为 JSON 字符串时,路径分隔符应该不是问题。
您的示例未显示 json 变量的类型和初始化,但您可以通过以下方式从 dict 获取 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);

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

【讨论】:

  • 它适用于您给定的 jsonDict,但是当我替换 NSData 的字典名称时,它会崩溃,并给出错误“原因:'JSON 写入 (NSURL) 中的类型无效'”。
  • 您的路径似乎存储为字典中的 NSURL 对象。首先使用 [NSURLobject absoluteString] 将它们转换为字符串。
猜你喜欢
  • 2021-08-11
  • 1970-01-01
  • 2019-01-08
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
相关资源
最近更新 更多