首页 关于 微信公众号
欢迎关注我的微信公众号

谈谈开发中的JSON

JSON的概念

JSON全称叫JavaScript Object Notation,是一种轻量级的文本数据交换格式。JSON采用完全独立于语言的文本格式。

JSON的语法特点

JSON语法是JavaScript对象表示语法的子集。JSON语法具有以下特点:数据在键值对中;数据由逗号分隔;花括号保存对象;方括号保存数组。

JSON的值

JSON值可以是:

JSON的结构

JSON有两种结构。JSON简单的说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种,通过这两种结构可以表示各种复杂的结构。

1、对象:对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,…}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。

{ "firstName":"John" , "lastName":"Doe" }

2、数组:数组在js中是中括号“[]”括起来的内容,数据结构为 [“java”,”javascript”,”vb”,…],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

JSON在开发中的应用

开发中无非就是Foundation对象封装成json作为请求参数,或者是网络请求得到的结果是json进行解析。

NSJSONSerialization的介绍

在开发中经常进行Foundation对象转化为json,json转化为Foundation对象。ios提供了一个叫NSJSONSerialization的类。

一个Foundation对象如果要转化为JSON,必须满足以下特点:

NSJSONSerialization提供了一个方法来检测一个Foundation对象能不能转化为JSON

+ (BOOL)isValidJSONObject:(id)obj;

利用以下方法来转化Foundation对象为JSON

/* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.
 */
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

JSON转化为Foundation对象

/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
   The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
 */
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

还提供了下面两个方法

/* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
 */
+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error;

/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
 */
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;

具体代码

Foundation转化为JSON对象

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"i can fly",@"title",@"4012",@"length",@"Tom",@"Singer", nil];
        if ([NSJSONSerialization isValidJSONObject:dict]) {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
            NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"json object:%@",json);
        }
        
/*
执行结果:
json object:{
  "title" : "i can fly",
  "Singer" : "Tom",
  "length" : "4012"
}
*/

Foundation转化为JSON数组

 NSArray *array = @[@"qn", @18, @"ya", @"wj"];
        BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
        if (isYes) {
            NSLog(@"可以转换");
            NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
//            [data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES];
            NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"json array:%@",json);
        } else {
            NSLog(@"JSON数据生成失败,请检查数据格式");
        }
        
/*
执行结果:
json array:["qn",18,"ya","wj"]
*/

Blog

Opinion

Project