我有一个字典,我需要通过使用字典生成一个JSON字符串。可以转换吗?你们能帮帮我吗?
当前回答
注:这个答案是在iOS 5发布之前给出的。
获取json-framework并执行以下操作:
#import "SBJsonWriter.h"
...
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:myDictionary];
[jsonWriter release];
myDictionary就是你的字典。
其他回答
现在不需要第三方类ios 5引入了Nsjsonserialization
NSString *urlString=@"Your url";
NSString *urlUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[[NSURL alloc]initWithString:urlUTF8];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:&myError];
Nslog(@"%@",res);
这段代码对于获取jsondata非常有用。
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打印风格
从ISO7开始,至少你可以用NSJSONSerialization轻松做到这一点。
您也可以通过在调试器中输入以下内容即时执行此操作
po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
推荐文章
- 如果模态ViewController演示样式为UIModalPresentationFormSheet, iPad键盘将不会解散
- 在UITableView中检测哪个UIButton被按下了
- 为iOS模拟器构建,但链接框架'****.framework'是为iOS构建的
- iOS更新后保留旧的启动屏幕和应用程序图标
- java8 LocalDate Jackson格式
- 如何象征崩溃日志Xcode?
- 我如何得到一个plist作为一个字典在Swift?
- Xcode - ld:没有为- lpods找到库
- 在Go中使用JSON Marshal的小写JSON键名
- 自动调整掩码大小编程vs接口生成器/ xib / nib
- jQuery发布JSON
- 将string (or char*)转换为wstring (or wchar_t*)
- NSUserDefaults -如何判断一个键是否存在
- Java的assertEquals方法可靠吗?
- 字符串作为SQL数据库的主键