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的解析。

126 thoughts on “NSJSONSerialization详细案例

  1. go perya

    Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is great, let alone the content!

  2. bcasino

    I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Excellent work!

  3. Cryptify Hub

    一个有意思的定位:它什么都“有”,又什么都不“有”。Cryptify Hub上有成百上千个链接,但每个链接点进去的内容都不归它管。它就是Web3/AI工具的大门口,进了门往哪走,全看你自己。

  4. 金钻体育应用

    Just wish to say your article is as astonishing. The clearness in your post is just spectacular and i could assume you are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the enjoyable work.

  5. 博源世界杯买球

    Simply desire to say your article is as amazing. The clearness in your post is simply great and i can assume you’re an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.

  6. 狮扑投注技巧

    Just wish to say your article is as amazing. The clarity in your post is simply excellent and i can assume you’re an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding work.

  7. 环亚体育平台

    Simply want to say your article is as astounding. The clarity in your post is simply spectacular and i could assume you’re an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding work.

  8. 申博体育网站

    Yesterday, while I was at work, my sister stole my iphone and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is totally off topic but I had to share it with someone!

  9. 必威彩票娱乐

    May I just say what a relief to discover someone who actually knows what they are discussing on the internet. You actually understand how to bring an issue to light and make it important. More people really need to look at this and understand this side of your story. I can’t believe you’re not more popular since you most certainly possess the gift.

发表评论

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