码迷,mamicode.com
首页 > 移动开发 > 详细

NSDictionary+JSON - iOS

时间:2018-09-18 19:17:08      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:details   error   ofo   开发   amp   常用   ati   跳转   sda   

日常开发中常用的一个相互转换的方法;

直接创建对应的类,引用如下方法即可实现;

具体 code 如下:

声明:

#import <Foundation/Foundation.h>
 
@interface NSDictionary (JSON)
 
- (NSString *)jsonString;
 
- (void)writeToJsonFile:(NSString *)path atomically:(BOOL)atomically;
 
+ (NSDictionary *)dictionaryWithContentsOfJsonFile:(NSString *)path;
 
 
 
@end

实现:

#import "NSDictionary+JSON.h"
#import "NSString+JSON.h"
 
@implementation NSDictionary (JSON)
 
- (NSString *)jsonString {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                       options:0
                                                         error:&error];
    if (error)
        return nil;
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}
 
- (void)writeToJsonFile:(NSString *)path atomically:(BOOL)atomically {
    NSData *content = [[self jsonString] dataUsingEncoding:NSUTF8StringEncoding];
    [content writeToFile:path atomically:atomically];
}
 
+ (NSDictionary *)dictionaryWithContentsOfJsonFile:(NSString *)path {
    NSError *error = nil;
    NSString *content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        return nil;
    }
    id result = [content jsonObject];
    if (![result isKindOfClass:[self class]]) {
        return nil;
    }
    return result;
}
 
 
 
@end

  

注:实现类中需要引入的类在如下飞机票中,具体详情请跳转查看.

NSString+JSON - iOS 机票如下: NSString+JSON - iOS

 

以上便是此次分享的内容,希望能对大家有所帮助!

 

NSDictionary+JSON - iOS

标签:details   error   ofo   开发   amp   常用   ati   跳转   sda   

原文地址:https://www.cnblogs.com/survivorsfyh/p/9670238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!