IOS转换和解析JSON数据

在IOS开发中常用到使用Json数据向服务器发送请求和接收数据,本例使用IOS5自带解析类NSJSONSerialization方法解析,无需导入包,IOS5支持,但是低版本IOS不支持。

1.首先建立数据模型

//  MyData.h
#import 
#import "SrtcJSONObject.h"
@interface MyData : NSObject <SrtcJSONObject>
@property (nonatomic, strong) NSString *userId;
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, strong) NSMutableArray *myRecords;
@end

myRecord是Record类型的数组

//  Record.h
#import 
#import "SrtcJSONObject.h"
@interface Record : NSObject <SrtcJSONObject>
@property (nonatomic, strong) NSString *ID;
@property (nonatomic, strong) NSString *date;
@property (nonatomic, strong) NSString *content;
@end

2.Json转换和解析方法
在SrtcJSONObject类里面声明Json转换的方法

//SrtcJSONObject.h
#import 
@protocol SrtcJSONObject <NSObject>
@optional - (NSData *) toJson;
@optional - (NSDictionary *) toJsonDictionary;
@optional - (void) fromJson:(NSData *)jsonData;
@optional - (void) fromJsonDictionary:(NSDictionary *)jsonDict;
@end

MyData.m里实现toJson和fromJson

//  MyData.m
#import "MyData.h"
#import "Record.h"
#define CHECK_NIL(value) ((value) == nil ? (@"") : (value))

@implementation MyData
- (NSData *) toJson {
    //Record类型的数组数据不能直接转换为Json,先转换为json字典
    NSMutableArray *recordArray = [[NSMutableArray alloc] init];
    if (self.myRecords) {
        [self.myRecords enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            Record *record = obj;
            //Record.m中实现toJsonDictionary
            [recordArray addObject:[record toJsonDictionary]];
        }];
    }
    //MyData转换为json字典
    NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              CHECK_NIL(self.userId), @"userId",
                              CHECK_NIL(self.userName), @"userName",
                              CHECK_NIL(recordArray), @"recordArray",
                              nil];

    NSError *error = nil;
    NSData *jsonData = nil;
    if ([NSJSONSerialization isValidJSONObject:jsonDict]) {
        //NSJSONSerialization中的dataWithJSONObject方法将字典数据转换为json数据
        jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
    }
    return jsonData;
}

- (void) fromJson:(NSData *)jsonData {
    if (jsonData) {
        NSError *error = nil;
        //JSONObjectWithData将json数据解析为字典
        NSDictionary *resultJson = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (resultJson) {
            [resultJson enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                //根据key值解析数据
                if ([key isEqualToString:@"userId"]) {
                    self.userId =  obj;
                } else if ([key isEqualToString:@"userName"]) {
                    self.userName = obj;
                } else if ([key isEqualToString:@"recordArray"]) {
                    NSArray *subArray = (NSArray *) obj;
                    self.myRecords = [[NSMutableArray alloc] initWithCapacity:[subArray count]];
                    if (subArray) {
                        [subArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                            Record *record = [[Record alloc] init];
                            //Record.m中实现fromJsonDictionary方法
                            [record fromJsonDictionary:obj];
                            [self.myRecords insertObject:record atIndex:idx];
                        }];
                    }
                }
            }];
        }
    }
}
@end

Record.m里实现toJsonDictionary和fromJsonDictionary

//  Record.m
#import "Record.h"
#define CHECK_NIL(value) ((value) == nil ? (@"") : (value))

@implementation Record
- (NSDictionary *) toJsonDictionary {
    NSDictionary *jsonDict = nil;
    jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:
                CHECK_NIL(self.ID), @"ID",
                CHECK_NIL(self.date), @"date",
                CHECK_NIL(self.content), @"content",
                nil];
    return jsonDict;
}

- (void) fromJsonDictionary:(NSDictionary *)jsonDict {
    if (jsonDict) {
        [jsonDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([key isEqualToString:@"ID"]) {
                self.ID = (NSString *)obj;
            } else if ([key isEqualToString:@"date"]) {
                self.date = (NSString *)obj;
            } else if ([key isEqualToString:@"content"]) {
                self.content = (NSString *)obj;
            }
        }];
    }
}
@end

3.创建数据转换json并解析
在ViewController.m的viewDidLoad方法中测试解析方法:

- (void)viewDidLoad {
    [super viewDidLoad];   
    NSMutableArray *records = [[NSMutableArray alloc] init];

    Record *record1 = [[Record alloc] init];
    record1.ID      = @"1";
    record1.date    = @"2015-04-11";
    record1.content = @"abc";

    Record *record2 = [[Record alloc] init];
    record2.ID      = @"1";
    record2.date    = @"2015-04-11";
    record2.content = @"efg";
    [records addObject:record1];
    [records addObject:record2];

    MyData *data   = [[MyData alloc] init];
    data.userId    = @"1001";
    data.userName  = @"user";
    data.myRecords = records;

    //使用MyData中的toJson方法转换成Json数据
    NSData *jsonData = [data toJson];
    NSLog(@"%@", [NSString stringWithUTF8String:[jsonData bytes]]);

    //使用MyData中的fromJson方法解析上面转换的Json数据
    MyData *resultData = [[MyData alloc] init];
    [resultData fromJson:jsonData];

    NSLog(@"userId: %@",resultData.userId);
    NSLog(@"userName: %@",resultData.userName);
    [resultData.myRecords enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL  *stop){
        Record *record = obj;
        NSLog(@"record%i: ID: %@; date: %@; content: %@;",index,record.ID,record.date,record.content);
    }];
}

4.输出结果

//jsonData
2016-04-15 17:06:25.654 JsonParseDemo[3586:60b] {
  "userName" : "user",
  "userId" : "1001",
  "recordArray" : [
    {
      "ID" : "1",
      "content" : "abc",
      "date" : "2015-04-11"
    },
    {
      "ID" : "1",
      "content" : "efg",
      "date" : "2015-04-11"
    }
  ]
}
//resultData
2016-04-15 17:06:25.660 JsonParseDemo[3586:60b] userId: 1001
2016-04-15 17:06:25.662 JsonParseDemo[3586:60b] userName: user
2016-04-15 17:06:25.664 JsonParseDemo[3586:60b] record0: ID: 1; date: 2015-04-11; content: abc;
2016-04-15 17:06:25.666 JsonParseDemo[3586:60b] record1: ID: 1; date: 2015-04-11; content: efg;

Demo下载地址:http://download.csdn.net/detail/u013935932/9492280

你可能感兴趣的:(IOS)