美文网首页
字典,数组JSON序列化

字典,数组JSON序列化

作者: 萝BAIBAI | 来源:发表于2015-11-14 22:50 被阅读235次

    字典序列化Json

    NSDictionary+BVJSONString.h

    
    #import <Foundation/Foundation.h>
    
    @interface NSDictionary (BVJSONString)
    
    - (NSString*)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
    
    @end
    

    NSDictionary+BVJSONString.m

    #import "NSDictionary+BVJSONString.h"
    
    @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
    

    数组序列化Json
    NSArray+BVJSONString.h

    #import <Foundation/Foundation.h>
    
    @interface NSArray (BVJSONString)
    
    - (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
    
    @end
    

    NSArray+BVJSONString.m

    #import "NSArray+BVJSONString.h"
    
    @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
    

    prettyPrint是方便打印查看,如果需要�使用的话还是设为NO,不然可能会出现一些你不需要的问题。

    相关文章

      网友评论

          本文标题:字典,数组JSON序列化

          本文链接:https://www.haomeiwen.com/subject/ecdkhttx.html