我有一个字典,我需要通过使用字典生成一个JSON字符串。可以转换吗?你们能帮帮我吗?
当前回答
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打印风格
其他回答
苹果在iOS 5.0和Mac OS X 10.7中添加了JSON解析器和序列化器。看到NSJSONSerialization。
要从NSDictionary或NSArray中生成JSON字符串,你不再需要导入任何第三方框架。
以下是如何做到这一点:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
将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就是你的字典。
从ISO7开始,至少你可以用NSJSONSerialization轻松做到这一点。
您也可以通过在调试器中输入以下内容即时执行此操作
po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 如何合并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字符串