NSJSONSerialization详细案例

今天带来的是NSJSONSerialization的详细案例。
NSJSONSerialization主要功能是:
将JSON转换成object 和 将object转为JSON。

那在这就要先明白JSON是什麽了?
JSON(JavaScript Object Notation)是一种轻量级的数据交换语言。
加之JSON具有良好的可读性,所以在移动开发上运用的越来越广泛。

JSON用于描述数据结构,有以下形式存在。
物件 (object):一个物件以「{」开始,并以「}」结束。一个物件包含一系列非排序的名称/值对,每个名称/值对之间使用「,」分割。
名称/值(collection):名称和值之间使用「:」隔开。
一般的形式是:
{“name” : “value”} 这就相当于iOS里面的NSDictionary [NSDictionary dictionaryWithObjectsAndKeys:@”value”, @”name”, nil]
一个名称是一个字串; 一个值可以是一个字串,一个数值,一个物件,一个布尔值,一个有序列表,或者一个null值。

值的有序列表(Array):一个或者多个值用「,」分割后,使用「[」,「]」括起来就形成了这样的列表,形如:
[“collection”, “collection”] 这个我就不解释吧。。。= =! [NSArray arrayWithObjects:@”collection”, @”collection”, nil]

字串:以””括起来的一串字符。
数值:一系列0-9的数字组合,可以为负数或者小数。还可以用「e」或者「E」表示为指数形式。
布林值:表示为 true 或者 false。

那麽将了这麽多废话,现在可以进入正题…..
首先NSJSONSerialization是必须在iOS 5.0以后的版本才可以使用的。
当然如果还在兼容4.3的你,可以考虑下除此之外很多好用的第三方库,如:JSONKit,SBJSON等。

本期辅助资料:
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
http://zh.wikipedia.org/zh-hk/JSON

JSON解析方法:
[objc]
+(id)parseJSONData:(NSData*)data{
NSError *error;
id jsonObject= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (!error) {//如果没有错误则返回解析后的数据
return jsonObject;
}else{
NSLog(@"UIBJSON resolve JSON err:%@",[error.userInfo objectForKey:@"NSLocalizedDescription"]);
return nil;
}
}
[/objc]

Object转换为JSON数据方法:
[objc]
+(NSData*)conversionJSONData:(id)object{
if ([NSJSONSerialization isValidJSONObject:object])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
//关于 NSJSONWritingPrettyPrinted 这个只是为了方便你看清结构,加多了换行。
if (!error) {
return jsonData;
}else{
NSLog(@"UIBJSON resolve JSON err:%@",[error.userInfo objectForKey:@"NSLocalizedDescription"]);
return nil;
}
}else{
// object不能被转为JSON
NSLog(@"The given object can’t be converted to JSON data.");
return nil;
}
}
[/objc]

如果出现object不能被转为JSON,
我们可以Command 进去上方 isValidJSONObject:
进行详细查看【具体将在下面说明】
[objc]
/* Returns YES if the given object can be converted to JSON data, NO otherwise. The object must have the following properties:
– Top level object is an NSArray or NSDictionary
– All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
– All dictionary keys are NSStrings
– NSNumbers are not NaN or infinity
Other rules may apply. Calling this method or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
*/

/*
– 顶层对象必须是NSArray 或者NSDictionary
– 所有对象必须是NSString NSNumber、NSArray NSDictionary或NSNull
– 所有dictionary的Key必须是NSString类型
– NSNumbers不能是非数值或者无穷大
*/
[/objc]

那麽 解析 和 转换 算是可以了。如果要用起来方便,你可以这样!!
新建一个NSObject的类,然后根据下面的代码COPY过去头文件
[objc]
//
// UIBJSON.h
//
//
// Created by kumadocs.com on 14-1-3.
// Copyright (c) 2014年 kumadocs.com . All rights reserved.
//

#import <Foundation/Foundation.h>

@interface UIBJSON : NSObject

@end

///////////// JSON parse to Object /////////////

@interface NSString (UIBDeserializing)
– (id)objectParseJSONString;
@end

@interface NSData (UIBDeserializing)
– (id)objectParseJSONData;
@end

///////////// Object conversion to JSON /////////////

@interface NSArray(UIBSerializing)
– (NSData *)arrayToJSONData;
– (NSString *)arrayToJSONString;
@end

@interface NSDictionary(UIBSerializing)
– (NSData *)dictionaryToJSONData;
– (NSString *)dictionaryToJSONString;
@end
[/objc]

接著是实现文件。也複製过去。
[objc]
//
// UIBJSON.m
//
//
// Created by kumadocs.com on 14-1-3.
// Copyright (c) 2014年 kumadocs.com . All rights reserved.
//

#import "UIBJSON.h"

@implementation UIBJSON
+(id)parseJSONData:(NSData*)data{
NSError *error;
id jsonObject= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (!error) {
return jsonObject;
}else{
NSLog(@"UIBJSON resolve JSON err:%@",[error.userInfo objectForKey:@"NSLocalizedDescription"]);
return nil;
}
}

+(NSData*)conversionJSONData:(id)object{
if ([NSJSONSerialization isValidJSONObject:object])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
if (!error) {
return jsonData;
}else{
NSLog(@"UIBJSON resolve JSON err:%@",[error.userInfo objectForKey:@"NSLocalizedDescription"]);
return nil;
}
}else{
NSLog(@"The given object can’t be converted to JSON data.");
return nil;
}

}
@end

#pragma mark – JSON parse to Object

@implementation NSString (UIBDeserializing)
– (id)objectParseJSONString{
NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
return [UIBJSON parseJSONData:data];
}
@end

@implementation NSData (UIBDeserializing)
– (id)objectParseJSONData{
return [UIBJSON parseJSONData:self];
}
@end

#pragma mark – Object conversion to JSON

@implementation NSArray(UIBSerializing)
– (NSData *)arrayToJSONData{
return [UIBJSON conversionJSONData:self];
}
– (NSString *)arrayToJSONString{
return [[NSString alloc] initWithData:[UIBJSON conversionJSONData:self] encoding:NSUTF8StringEncoding];
}
@end

@implementation NSDictionary(UIBSerializing)
– (NSData *)dictionaryToJSONData{
return [UIBJSON conversionJSONData:self];
}
– (NSString *)dictionaryToJSONString{
return [[NSString alloc] initWithData:[UIBJSON conversionJSONData:self] encoding:NSUTF8StringEncoding];
}
@end
[/objc]

之后每次使用的时候,仅需加入头 #import “UIBJSON.h”
接著在代码中如此使用即可:
[objc]
NSString *strJSON = @"{\"name\" : \"value\"} ";
NSLog(@"JSON string -> object :%@",[strJSON objectParseJSONString]);
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"name",nil];
NSLog(@"dictionary -> JSON string :%@",[dict dictionaryToJSONString]);
NSArray *ar = [NSArray arrayWithObjects:@"collection", @"collection", nil];
NSLog(@"array -> JSON string :%@",[ar arrayToJSONString]);
[/objc]

本期到此结束,下期将是关于XML的解析。

89 thoughts on “NSJSONSerialization详细案例

Kllnzq进行回复 取消回复

电子邮件地址不会被公开。