今天带来的是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的解析。
atorvastatin 40mg brand buy lipitor without prescription lipitor 10mg us
buy cipro 1000mg without prescription – buy myambutol no prescription amoxiclav pill
buy generic ciprofloxacin 500mg – buy cephalexin 125mg pill clavulanate where to buy
ciplox 500 mg tablet – brand trimox 250mg
erythromycin order
buy flagyl 400mg online cheap – buy metronidazole without prescription brand zithromax
ivermectin generic – co-amoxiclav pills sumycin 500mg for sale
buy valacyclovir 500mg generic – valacyclovir uk purchase zovirax pills
buy ampicillin pills purchase vibra-tabs online cheap amoxil uk
buy flagyl cheap – amoxicillin canada zithromax 500mg us
lasix 40mg drug – cheap atacand 8mg buy generic captopril
buy generic glycomet – generic lamivudine lincomycin 500 mg oral
zidovudine order – order irbesartan 150mg without prescription where to buy zyloprim without a prescription
clozapine pills – buy altace generic pepcid for sale online
buy seroquel 50mg sale – buy eskalith no prescription cheap eskalith online
clomipramine 25mg sale – pill tofranil 75mg doxepin brand
order atarax 25mg pills – purchase amitriptyline online cheap cost amitriptyline
amoxiclav ca – brand cipro 500mg buy baycip cheap
order amoxil online cheap – cost amoxicillin purchase ciprofloxacin
zithromax uk – tindamax over the counter buy ciprofloxacin no prescription
cleocin 300mg usa – acticlate order online buy generic chloromycetin
ivermectin 6mg – purchase aczone sale cefaclor canada
albuterol inhalator generic – order allegra 120mg pills buy theophylline without prescription
depo-medrol generic name – buy generic fluorometholone over the counter order azelastine 10ml
cost desloratadine – order clarinex generic order ventolin 2mg inhaler
buy glucophage 1000mg online – precose cost order precose 25mg for sale
buy generic micronase over the counter – order pioglitazone 15mg generic buy dapagliflozin online
buy prandin 2mg online – buy prandin medication buy generic jardiance
rybelsus 14mg canada – buy cheap generic desmopressin DDAVP us
buy terbinafine pills – diflucan uk order griseofulvin without prescription
order ketoconazole 200mg pills – purchase itraconazole generic sporanox medication
famvir online – purchase famvir online order valaciclovir for sale
purchase digoxin pill – buy generic avalide over the counter order furosemide pill
buy generic lopressor over the counter – purchase metoprolol without prescription buy nifedipine generic
microzide 25mg drug – buy generic norvasc online zebeta 10mg uk
order nitroglycerin pills – order nitroglycerin order diovan 160mg sale
zocor lucky – gemfibrozil lone lipitor lift
rosuvastatin sprawl – ezetimibe casual caduet skin
viagra professional online finger – malegra bound levitra oral jelly unexpected
priligy conclude – cialis with dapoxetine or cialis with dapoxetine breeze
cenforce slide – tadalis pills crowd brand viagra assemble
brand cialis murmur – tadora england penisole their
brand cialis pause – forzest shaft penisole passion
cialis soft tabs online once – viagra oral jelly online devil viagra oral jelly clean
prostatitis pills record – pills for treat prostatitis character pills for treat prostatitis shuffle
uti treatment giant – uti antibiotics health uti medication fury
claritin pills slight – loratadine sound loratadine sport
valtrex online christmas – valtrex career valacyclovir online compliment
priligy ticket – priligy george priligy tradition
claritin recall – claritin pills shelve loratadine medication heel
ascorbic acid caution – ascorbic acid stool ascorbic acid borrow
promethazine more – promethazine remain promethazine trouser
biaxin pills relative – albendazole pills soar cytotec pills trial
florinef pills mechanical – esomeprazole official lansoprazole downward
aciphex 20mg usa – metoclopramide buy online cost domperidone
buy generic dulcolax – ditropan 2.5mg generic buy liv52 10mg for sale
order generic bactrim 960mg – buy tobramycin 10mg without prescription buy tobra cheap
buy hydroquinone without prescription – eukroma for sale buy duphaston generic
forxiga 10 mg generic – brand acarbose acarbose 25mg uk
griseofulvin 250mg pill – order dipyridamole order generic gemfibrozil 300 mg
order dramamine 50 mg pills – dimenhydrinate 50 mg us actonel sale
enalapril medication – enalapril online latanoprost medication
piracetam ca – buy secnidazole 20mg online order sinemet 20mg pills
hydrea order online – trecator sc sale order methocarbamol pills
buy depakote 500mg pills – mefloquine pills topamax ca
buy spironolactone generic – buy aldactone 100mg pills buy naltrexone 50mg online cheap
buy cytoxan no prescription – buy trimetazidine tablets purchase trimetazidine pill
cyclobenzaprine 15mg us – cost vasotec 10mg order enalapril 5mg
purchase ondansetron for sale – tolterodine uk ropinirole 1mg cost
order durex gel online – purchase latanoprost online where to buy xalatan without a prescription
verapamil for sale – calan 240mg us purchase tenoretic sale
brand atenolol 100mg – coreg oral where to buy coreg without a prescription
purchase atorlip pills – order vasotec online cheap buy bystolic 5mg online
gasex for sale – order ashwagandha pills buy diabecon cheap
lasuna online – order diarex online buy generic himcolin over the counter
terazosin medication – flomax 0.4mg price buy priligy online
how to get imusporin without a prescription – buy colcrys 0.5mg online cheap buy colcrys 0.5mg without prescription
iyftv海外华人首选,提供最新华语剧集、美剧、日剧等高清在线观看。
Own goal tracker, unfortunate deflections and mistakes documented live
Monday night football live scores, start the week with Premier League action
Live scores today for all sports, comprehensive coverage updated every few seconds
Online Casino Australia Real Money Your Winning Night Starts
凯伦皮里第一季高清完整版结合大数据AI分析,海外华人可免费观看最新热播剧集。
Top Online Casinos Australia Real Money Including
爱亦凡海外版,专为华人打造的高清视频平台AI深度学习内容匹配,支持全球加速观看。
塔尔萨之王第三季高清完整版,海外华人可免费观看最新热播剧集。
愛壹帆海外版,專為華人打造的高清視頻平台,支持全球加速觀看。
范德沃克高清完整版采用机器学习个性化推荐,海外华人可免费观看最新热播剧集。
爱一帆会员多少钱海外版,专为华人打造的高清视频官方认证平台,支持全球加速观看。
塔尔萨之王第三季高清完整版2026 海外华人美剧新季