在iOS中从NSDictionary生成JSON字符串

Cha*_*har 333 string json objective-c ios

我有一个dictionary我需要生成一个JSON string使用dictionary.有可能转换它吗?你能帮忙吗?

Gui*_*ume 745

Apple在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];
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的建议......让项目拥有大量第三方库真的很烦人. (86认同)
  • @OMGPOP - `[NSJSONSerialization JSONObjectWithData:options:error:]`从给定的JSON数据返回一个Foundation objec (5认同)
  • 转换为JSON对象的极好解决方案.做得好..:) (3认同)

Ben*_*ton 231

以下是NSArray和NSDictionary的类别,使这非常容易.我添加了一个漂亮的打印选项(新行和标签,以便于阅读).

@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
Run Code Online (Sandbox Code Playgroud)

.

@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
Run Code Online (Sandbox Code Playgroud)

.

@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
Run Code Online (Sandbox Code Playgroud)

.

@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
Run Code Online (Sandbox Code Playgroud)

  • 如果我们创建一个NSObject类并使用相同的方法,它适用于NSArray和NSDictionary.无需编写两个单独的文件/接口.如果出错,它应该返回nil. (8认同)
  • 没关系,文档说"结果数据是用UTF-8编码的." (5认同)

job*_*ima 59

要将NSDictionary转换为NSString:

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err]; 
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Run Code Online (Sandbox Code Playgroud)


Nic*_*ver 35

注意:此答案是在iOS 5发布之前给出的.

获取json框架并执行此操作:

#import "SBJsonWriter.h"

...

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

NSString *jsonString = [jsonWriter stringWithObject:myDictionary];  

[jsonWriter release];
Run Code Online (Sandbox Code Playgroud)

myDictionary 将是你的字典.


And*_*ndy 24

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

po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
Run Code Online (Sandbox Code Playgroud)

  • 这在LLDB目前不起作用:`错误:使用未声明的标识符'NSUTF8StringEncoding' (5认同)
  • 硬编码常数有点可怕.为什么不使用NSUTF8StringEncoding等? (4认同)
  • 非常适合那些您希望使用外部json编辑器快速检查字典的时刻! (2认同)

Mee*_*shi 14

您可以传递数组或字典.在这里,我正在使用NSMutableDictionary.

NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
Run Code Online (Sandbox Code Playgroud)

要从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);
Run Code Online (Sandbox Code Playgroud)


小智 12

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];
Run Code Online (Sandbox Code Playgroud)


Kin*_*ard 7

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
}
Run Code Online (Sandbox Code Playgroud)