字典,数组JSON序列化

字典序列化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,不然可能会出现一些你不需要的问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 2,670评论 1 14
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,303评论 19 139
  • 1.badgeVaule气泡提示 2.git终端命令方法> pwd查看全部 >cd>ls >之后桌面找到文件夹内容...
    i得深刻方得S阅读 4,925评论 1 9
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,502评论 30 472
  • 人的天资差别太大了,有的人轻而易举做到事,任你怎么努力都不及他几分之一。能学的来吗?智商是最大的障碍! 除...
    阿清哥阅读 177评论 0 0

友情链接更多精彩内容