在iOS中从NSDictionary生成JSON字符串

我有一个dictionary,我需要使用dictionary生成一个JSON string。可以转换吗?你们能帮帮我吗?

309336 次浏览

注:这个答案是在iOS 5发布之前给出的。

获取json-framework并这样做:

#import "SBJsonWriter.h"


...


SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];


NSString *jsonString = [jsonWriter stringWithObject:myDictionary];


[jsonWriter release];

myDictionary将是你的字典。

苹果在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];
}

这里有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

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

您也可以通过在调试器中输入以下内容即时执行此操作

po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];

从ISO7开始,至少你可以用NSJSONSerialization轻松做到这一点。

将NSDictionary转换为NSString:

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
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];

在Swift中,我创建了以下helper函数:

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)")
}
}

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
}

可以传递数组或字典。这里,我使用NSMutableDictionary。

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

为了从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);
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打印风格

下面是斯威夫特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()

这将在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)