您当前的位置: 首页 >  网络

white camel

暂无认证

  • 1浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

iOS开发网络篇 一一 JSON解析

white camel 发布时间:2017-12-17 13:53:43 ,浏览量:1

1. 什么是JSON?

1). JSON是一种轻量级的数据格式,一般用于数据交互.

2). 服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外)

3). JSON的格式很像OC中的字典和数组

{ "name" : "jack" , "age" :  10 }

{ "names" : [ "jack" , "rose" , "jim" ] }

标准JSON格式的注意:  key必须用双引号

2. 序列化 和 反序列化

序列化: OC对象 ---> JSON/XML

反序列化: JSON/XML ---> OC对象

转换对照表

     JOSN   OC

     {}       @{}

     []       @[]

     ""       @""

     false    NSNumber 0

     true     NSNumber 1

     null      NSNull为空

JSON解析方案:

  a.第三方框架  JSONKit\SBJSON\TouchJSON

  b.苹果原生(NSJSONSerialization)性能最好

NSJSONSerialization 常见方法:

JSON数据  —> OC对象
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

OC对象 —> JSON数据 
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

OC对象是否可转
+ (BOOL)isValidJSONObject:(id)obj;

注意: 以下代码 包括: 

1. 序列化(OC对象 ---> JSON数据)

注意点:  并不是所有的OC对象都能转为JSON(NSString类型就不行)

序列化的要求: 

      -最外层必须是 NSArray or NSDictionary

       -所有的元素必须是 NSString, NSNumber, NSArray, NSDictionary, or NSNull

        - 字典中所有的key都必须是 NSString类型的

       - NSNumbers不能死无穷大

如果不满足以上要求: 为了防止程序崩溃, 需要做一个oc对象是否能转为JSON的判断.

    // 判断oc对象是否能转
    BOOL isValid = [NSJSONSerialization isValidJSONObject:dictM];
    if (!isValid) {
        NSLog(@"%zd",isValid);
        return;
    }

2. 反序列化(JSON数据 ---> OC对象)

注意点: 如果解析 非字典/数组的数据, 只能使用 NSJSONReadingAllowFragments这个枚举

kNilOptions == 0

3. JSON 和 OC对象的关系

4. plist数据 转为 JSON数据

//
//  ViewController.m
//  05掌握-JSON解析
//
//  Created by 朝阳 on 2017/12/7.
//  Copyright © 2017年 sunny. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self OCToJson];
}

// 序列化(OC对象 --> JSON)
- (void)OCToJson
{
    NSDictionary *dictM = @{
                            @"name" : @"ZY",
                            @"age" : @19
                            };
    NSArray *arrayM = @[@"44",@"123"];
    // 注意: 并不是所有的OC对象都能转为JSON(NSString类型就不行)
    NSString *strM = @"guizhaoyang";
    
    /*
     - 最外层必须是 NSArray or NSDictionary
     - 所有的元素必须是 NSString, NSNumber, NSArray, NSDictionary, or NSNull
     - 字典中所有的key都必须是 NSString类型的
     - NSNumbers不能死无穷大
     */
    // 判断oc对象是否能转
    BOOL isValid = [NSJSONSerialization isValidJSONObject:dictM];
    if (!isValid) {
        NSLog(@"%zd",isValid);
        return;
    }
    /*
     param1:要转换的OC对象
     param2: 排版,美观  NSJSONWritingPrettyPrinted
     param3:错误信息
     */
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictM options:NSJSONWritingPrettyPrinted error:nil];
    NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}

// 反序列化(JSON --> OC对象)
- (void)JsonToObject
{
    //1. 确定URL
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    //2. 创建请求对象
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    //3. 发送异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // data(响应体) ---> 本质就是字符串
        //4. 解析数据
        // 反序列化 JSON--->OC对象
        /*
         NSJSONReadingMutableContainers = (1UL             
关注
打赏
1661428283
查看更多评论
0.0380s