我有一个字典,我需要通过使用字典生成一个JSON字符串。可以转换吗?你们能帮帮我吗?
当前回答
在Swift 2.0版本中:
class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
var jsonStr: String?
if data != nil {
jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
}
return jsonStr
}
其他回答
将NSDictionary转换为NSString:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
注:这个答案是在iOS 5发布之前给出的。
获取json-framework并执行以下操作:
#import "SBJsonWriter.h"
...
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:myDictionary];
[jsonWriter release];
myDictionary就是你的字典。
public func jsonPrint(_ o: NSObject, spacing: String = "", after: String = "", before: String = "") {
let newSpacing = spacing + " "
if o.isArray() {
print(before + "[")
if let a = o as? Array<NSObject> {
for object in a {
jsonPrint(object, spacing: newSpacing, after: object == a.last! ? "" : ",", before: newSpacing)
}
}
print(spacing + "]" + after)
} else {
if o.isDictionary() {
print(before + "{")
if let a = o as? Dictionary<NSObject, NSObject> {
for (key, val) in a {
jsonPrint(val, spacing: newSpacing, after: ",", before: newSpacing + key.description + " = ")
}
}
print(spacing + "}" + after)
} else {
print(before + o.description + after)
}
}
}
这个非常接近最初的Objective-C打印风格
这将在swift4和swift5中工作。
let dataDict = "the dictionary you want to convert in jsonString"
let jsonData = try! JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
print(jsonString)
这是Swift 4的版本
extension NSDictionary{
func toString() throws -> String? {
do {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(data: data, encoding: .utf8)
}
catch (let error){
throw error
}
}
}
使用的例子
do{
let jsonString = try dic.toString()
}
catch( let error){
print(error.localizedDescription)
}
或者如果你确定它是有效的字典,那么你可以使用
let jsonString = try? dic.toString()
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 如何合并2 JSON对象从2个文件使用jq?
- Xcode构建失败“架构x86_64未定义的符号”
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- printf()和puts()在C语言中的区别是什么?
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- 如何在Kotlin解析JSON ?
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- JSON文件的蒙古导入
- jQuery -替换字符串中某个字符的所有实例
- Base64长度计算?
- 使用split("|")按管道符号拆分Java字符串