在iOS中从NSDictionary生成JSONstring

我有一个dictionary我需要通过使用dictionary生成一个JSON string 。 是否有可能将其转换? 你们能帮忙吗?

这里是NSArray和NSDictionary的类别,使这超级简单。 我已经添加了一个漂亮的选项(换行符和制表符更容易阅读)。

 @interface NSDictionary (BVJSONString) -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint; @end 

 @implementation NSDictionary (BVJSONString) -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0) error:&error]; if (! jsonData) { NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription); return @"{}"; } else { return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } } @end 

 @interface NSArray (BVJSONString) - (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint; @end 

 @implementation NSArray (BVJSONString) -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0) error:&error]; if (! jsonData) { NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription); return @"[]"; } else { return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } } @end 

Apple在iOS 5.0和Mac OS X 10.7中添加了JSONparsing器和序列化程序。 请参阅NSJSONSerialization 。

要从NSDictionary或NSArray生成一个JSONstring,您不需要导入任何第三方框架了。

这里是如何做到这一点:

 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框架,并执行此操作:

 #import "SBJsonWriter.h" ... SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init]; NSString *jsonString = [jsonWriter stringWithObject:myDictionary]; [jsonWriter release]; 

myDictionary将是你的字典。

您也可以通过在debugging器中input以下内容来执行此操作

 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]; 

你可以传递数组或字典。 在这里,我正在采取NSMutableDictionary。

 NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init]; [contentDictionary setValue:@"a" forKey:@"b"]; [contentDictionary setValue:@"c" forKey:@"d"]; 

要从NSDictionary或NSArray生成JSONstring,您不需要导入任何第三方框架。 只需使用以下代码:

 NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contentDictionary // Here you can pass array or dictionary options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string error:&error]; NSString *jsonString; if (jsonData) { jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; //This is your JSON String //NSUTF8StringEncoding encodes special characters using an escaping scheme } else { NSLog(@"Got an error: %@", error); jsonString = @""; } NSLog(@"Your JSON String is %@", jsonString); 

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 } 

现在不需要第三方类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。

在Swift中,我创build了以下帮助函数:

 class func nsobjectToJSON(swiftObject: NSObject) { var jsonCreationError: NSError? let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(swiftObject, options: NSJSONWritingOptions.PrettyPrinted, error: &jsonCreationError)! if jsonCreationError != nil { println("Errors: \(jsonCreationError)") } else { // everything is fine and we have our json stored as an NSData object. We can convert into NSString let strJSON : NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! println("\(strJSON)") } } 

至less在ISO7中,你可以使用NSJSONSerialization轻松地做到这一点 。

 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打印样式非常接近