日常开发中常用的一个相互转换的方法;
直接创建对应的类,引用如下方法即可实现;
具体 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
以上便是此次分享的内容,希望能对大家有所帮助!