在 iOS 中从 NSDictionary 生成 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6368867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate JSON string from NSDictionary in iOS
提问by ChandraSekhar
I have a dictionary
I need to generate a JSON string
by using dictionary
. Is it possible to convert it? Can you guys please help on this?
我有一个dictionary
我需要JSON string
使用dictionary
. 可以转换吗?你们能帮忙解决这个问题吗?
采纳答案by Ben Clayton
Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).
这里是 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(@"%s: error: %@", __func__, 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(@"%s: error: %@", __func__, error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
回答by Guillaume
Apple added a JSON parser and serializer in iOS 5.0 and Mac OS X 10.7. See NSJSONSerialization.
Apple 在 iOS 5.0 和 Mac OS X 10.7 中添加了 JSON 解析器和序列化器。请参阅NSJSONSerialization。
To generate a JSON string from a NSDictionary or NSArray, you do not need to import any third party framework anymore.
要从 NSDictionary 或 NSArray 生成 JSON 字符串,您不再需要导入任何第三方框架。
Here is how to do it:
这是如何做到的:
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];
}
回答by jobima
To convert a NSDictionary to a NSString:
要将 NSDictionary 转换为 NSString:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
回答by Nick Weaver
NOTE: This answer was given before iOS 5 was released.
注意:这个答案是在 iOS 5 发布之前给出的。
Get the json-frameworkand do this:
获取json-framework并执行以下操作:
#import "SBJsonWriter.h"
...
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:myDictionary];
[jsonWriter release];
myDictionary
will be your dictionary.
myDictionary
将是你的字典。
回答by Andy
You can also do this on-the-fly by entering the following into the debugger
您也可以通过在调试器中输入以下内容来即时执行此操作
po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
回答by Meet Doshi
You can pass array or dictionary. Here, I am taking NSMutableDictionary.
您可以传递数组或字典。在这里,我正在使用 NSMutableDictionary。
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
To generate a JSON string from a NSDictionary or NSArray, You don't need to import any third party framework. Just use following code:-
要从 NSDictionary 或 NSArray 生成 JSON 字符串,您不需要导入任何第三方框架。只需使用以下代码:-
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);
回答by user2885077
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];
回答by King-Wizard
In Swift (version 2.0):
在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
}
回答by mahesh chowdary
Now no need third party classes ios 5 introduced Nsjsonserialization
现在不需要第三方类 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);
this code can useful for getting jsondata.
此代码可用于获取 jsondata。
回答by James Laurenstin
In Swift, I've created the following helper function:
在 Swift 中,我创建了以下辅助函数:
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)")
}
}