标签:
目前功能
将NSObject子类转成JSON格式
对象模型 -》 属性列表 -》 JSON格式
JSON和对象模型之间来回转换,
转到属性列表后用NSJSONSerialization和JSON之间转换。
1 // 2 // JSON HELPER.h 3 // JSON helper 4 // 5 // Created by 彭威 on 15/7/21. 6 // Copyright (c) 2015年 biophy.nju.edu.cn. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 #import <objc/runtime.h> 11 @interface JSON_HELPER : NSObject 12 @property (nonatomic,strong) NSDateFormatter *dateFormatter; 13 - (NSData *)dataFromObject:(id) obj; 14 @end 15 16 17 // 18 // JSON HELPER.m 19 // JSON helper 20 // 21 // Created by 彭威 on 15/7/21. 22 // Copyright (c) 2015年 biophy.nju.edu.cn. All rights reserved. 23 // 24 25 #import "JSON_HELPER.h" 26 27 28 @implementation JSON_HELPER 29 30 31 - (NSData *)dataFromObject:(id)obj{ 32 return [NSJSONSerialization dataWithJSONObject:[self dicFromObject:obj] options:NSJSONWritingPrettyPrinted error:nil]; 33 } 34 - (id) dicFromObject:(id) obj 35 { 36 if (!obj) { 37 return nil; 38 } 39 if([obj isKindOfClass:[NSString class]]){ 40 return obj; 41 }else if ([obj isKindOfClass:[NSDate class]]){ 42 return [self.dateFormatter stringFromDate:obj]; 43 }else if ([obj isKindOfClass:[NSNumber class]]){ 44 return [NSString stringWithFormat:@"%@",obj]; 45 }else if ([obj isKindOfClass:[NSArray class]]) { 46 NSMutableArray *jsonArr = [[NSMutableArray alloc] init]; 47 for (id subObj in (NSArray *)obj) { 48 [jsonArr addObject:[self dicFromObject:subObj]]; 49 } 50 return jsonArr; 51 } else if ([obj isKindOfClass:[NSDictionary class]]){ 52 NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init]; 53 NSArray *key = [(NSDictionary *)obj allKeys]; 54 for (NSString *subObjKey in key) { 55 id value = [self dicFromObject:obj[subObjKey]]; 56 [jsonDic setValue:value forKey:subObjKey]; 57 } 58 return jsonDic; 59 }else{ 60 NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init]; 61 u_int count; 62 objc_property_t* properties = class_copyPropertyList([obj class], &count); 63 for (int i = 0; i < count ; i++) { 64 const char* propertyName = property_getName(properties[i]); 65 NSString *propName = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]; 66 id propValue = [obj valueForKey:propName]; 67 id propJsonValue = [self dicFromObject:propValue]; 68 [jsonDic setValue:propJsonValue forKey:propName]; 69 } 70 free(properties); 71 return jsonDic; 72 73 } 74 } 75 - (NSDateFormatter *)dateFormatter{ 76 if (!_dateFormatter) { 77 _dateFormatter = [[NSDateFormatter alloc]init]; 78 [_dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 79 } 80 return _dateFormatter; 81 } 82 @end
标签:
原文地址:http://www.cnblogs.com/weierpeng/p/4665865.html