ios中解析json对象基类
这个是对上面一篇写的一个解析json对象的基类
- @interface BaseObjectFromJson : NSObject
- + (id) objectWithDict:(NSDictionary*)dict withClassName:(NSString*)className;
- + (NSArray*) objectsWithArray:(NSArray*)array withClassName:(NSString*)className;
- - (id) initWithDict:(NSDictionary*)dict;
- - (NSString*) propertyClassName:(NSString*)propertyName;
- @end
- //
- // BaseObjectFromJson.m
- // xxoo
- //
- // Created by Tommy on 13-11-5.
- // Copyright (c) 2013年 Tommy. All rights reserved.
- //
- #import "BaseObjectFromJson.h"
- #import "objcUtils.h"
- @implementation BaseObjectFromJson
- + (id) objectWithDict:(NSDictionary*)dict withClassName:(NSString*)className{
- Class objClass = NSClassFromString(className);
- BaseObjectFromJson* object = nil;
- if(objClass){
- object = [[objClass alloc] initWithDict:dict];
- }else{
- NSAssert(0, @"Unknown class:%@",className);
- }
- return object;
- }
- + (NSArray*) objectsWithArray:(NSArray*)array withClassName:(NSString*)className{
- Class objClass = NSClassFromString(className);
- BaseObjectFromJson* object = nil;
- NSMutableArray* objArray = nil;
- if(objClass){
- objArray = [NSMutableArray new];
- for (NSDictionary* dict in array){
- object = [[objClass alloc] initWithDict:dict];
- [objArray addObject:object];
- }
- }else{
- NSAssert(0, @"Unknown class:%@",className);
- }
- return objArray;
- }
- - (NSString*) description{
- NSMutableString* desc = [NSMutableString new];
- NSArray* propertyArray = getPropertyNameList(self);
- [desc appendString:@"{\r"];
- for (NSString* key in propertyArray) {
- [desc appendFormat:@" %@ : %@\r",key,[self valueForKey:key]];
- }
- [desc appendString:@"\r}"];
- return desc ;
- }
- - (id) initWithDict:(NSDictionary*)dict{
- NSArray* propertyArray = getPropertyNameList(self);
- for (NSString* key in propertyArray) {
- @try{
- if([dict[key] isKindOfClass:[NSArray class]]){
- NSString* className = [self propertyClassName:key];
- NSArray* array = [BaseObjectFromJson objectsWithArray:dict[key] withClassName:className?className:key];
- [self setValue:array forKey:key];
- }else if([dict[key] isKindOfClass:[NSDictionary class]]){
- [self setValue:[BaseObjectFromJson objectWithDict:dict[key] withClassName:key]forKey:key];
- }else{
- [self setValue:dict[key] forKey:key];
- }
- }@catch (NSException *exception) {
- NSLog(@"except:%@:%@",key,dict[key]);
- }
- }
- return self;
- }
- - (NSString*) propertyClassName:(NSString*)propertyName{
- return nil;
- }
- @end
- 这个demo很简单,用的还是上一篇中的例子。
- NSString* jsonString = request.responseString;
- NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *jsonObj = [jsonData objectFromJSONData];
- Result* result = [SearchResult objectWithDict:jsonObj withClassName:@"Result"];
如果一个需要对一个json对象的解析中不存在数组之类的,就直接继承就行,什么都不用写。如果有数组的话,就需要重载
- - (NSString*) propertyClassName:(NSString*)propertyName这个方法就行。这样就可以找到正确的类进行解析了。