首页 文章

在iOS中从NSDictionary生成JSON字符串

提问于
浏览
310

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

13 回答

  • 1

    在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)")
        }
    }
    
  • -1

    至于ISO7,至少你可以用NSJSONSerialization轻松完成 .

  • 7

    以下是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
    
  • 12

    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];
    }
    
  • 1

    要将NSDictionary转换为NSString:

    NSError * err;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err]; 
    NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
  • 213

    NOTE: This answer was given before iOS 5 was released.

    获取json-framework并执行此操作:

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

    myDictionary 将是你的字典 .

  • 3

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

    po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
    
  • 58
    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];
    
  • 23

    您可以传递数组或字典 . 在这里,我正在使用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);
    
  • 713

    Swift (version 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
    }
    
  • 34

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

  • 12

    这是 Swift 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()
    
  • 0
    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打印样式

相关问题