iOS-Json 解析

在工程中导入AFNetworking的库以及ZJModelTool库

json 解析:

#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
   -( void )downloadData
{
    NSString *urlString = [NSString stringWithFormat:self.urlString,_page,_categoryId];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];


    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {


        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *apps = dict[@"applications"];
        for (NSDictionary *appDict in apps) {
            
            //[ZJModelTool createModelWithDictionary:appDict modelName:@"AppModel"];
            AppModel *model = [[AppModel alloc] init];
            [model setValuesForKeysWithDictionary:appDict];
            NSLog(@"%@",model.name);
            model.desc = appDict[@"description"];
            [_dataArray addObject:model];
        }
        
        [_tableView reloadData];
  
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
}

ZJModelTool 是一个代码创建 Model 模板的代码库,不需更改,可以直接使用。

ZJModelTool.h

#import 
@interface ZJModelTool : NSObject
+(void)createModelWithDictionary:(NSDictionary *)dict modelName:(NSString *)modelName;
@end

ZJModelTool.m

#import "ZJModelTool.h"

@implementation ZJModelTool
//代码创建model类
+(void)createModelWithDictionary:(NSDictionary *)dict modelName:(NSString *)modelName
{
    printf("\n@interface %s :NSObject\n",modelName.UTF8String);
    for (NSString *key in dict) {
        NSString *type = ([dict[key] isKindOfClass:[NSNumber class]])?@"NSNumber":@"NSString";
        printf("@property (nonatomic,copy) %s *%s;\n",type.UTF8String,key.UTF8String);
    }
    printf("@end\n");
    
}
@end

你可能感兴趣的:(iOS-Json 解析)