iOS解析JSON

iOS網(wǎng)絡

  • GET:在請求URL后面以?的形式跟上發(fā)送給服務器的參數(shù),多個參數(shù)之間用&隔開

  • POS:發(fā)送給服務器的參數(shù)全部放在請求體重,理論上post傳遞的數(shù)據(jù)量沒有限制。

  • 如果只是單純的獲取數(shù)據(jù),數(shù)據(jù)查詢,建議使用GET,其他用POST

  • 1.0 JSON解析

  • 1.1 JSON簡單介紹

    001 問:什么是JSON
    答:
    (1)JSON是一種輕量級的數(shù)據(jù)格式,一般用于數(shù)據(jù)交互
    (2)服務器返回給客戶端的數(shù)據(jù),一般都是JSON格式或者XML格式(文件下載除外)
    002 相關說明
    (1)JSON的格式很像OC中的字典和數(shù)組
    (2)標準JSON格式key必須是雙引號
    003 JSON解析方案
    a.第三方框架 JSONKit\SBJSON\TouchJSON
    b.蘋果原生(NSJSONSerialization)

  • 1.2 JSON解析相關代碼

(1)json數(shù)據(jù)->OC對象

//把json數(shù)據(jù)轉換為OC對象
-(void)jsonToOC
{
    //1. 確定url路徑
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=33&pwd=33&type=JSON"];

    //2.創(chuàng)建一個請求對象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //3.使用NSURLSession發(fā)送一個異步請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        //4.當接收到服務器響應的數(shù)據(jù)后,解析數(shù)據(jù)(JSON--->OC)

        /*
         第一個參數(shù):要解析的JSON數(shù)據(jù),是NSData類型也就是二進制數(shù)據(jù)
         第二個參數(shù): 解析JSON的可選配置參數(shù)
         NSJSONReadingMutableContainers 解析出來的字典和數(shù)組是可變的
         NSJSONReadingMutableLeaves 解析出來的對象中的字符串是可變的  iOS7以后有問題
         NSJSONReadingAllowFragments 被解析的JSON數(shù)據(jù)如果既不是字典也不是數(shù)組, 那么就必須使用這個
         */
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@",dict);

    }];
}

(2)OC對象->JSON對象

 //1.要轉換成JSON數(shù)據(jù)的OC對象*這里是一個字典
    NSDictionary *dictM = @{
                            @"name":@"wendingding",
                            @"age":@100,
                            @"height":@1.72
                            };
    //2.OC->JSON
    /*
     注意:可以通過+ (BOOL)isValidJSONObject:(id)obj;方法判斷當前OC對象能否轉換為JSON數(shù)據(jù)
     具體限制:
         1.obj 是NSArray 或 NSDictionay 以及他們派生出來的子類
         2.obj 包含的所有對象是NSString,NSNumber,NSArray,NSDictionary 或NSNull
         3.字典中所有的key必須是NSString類型的
         4.NSNumber的對象不能是NaN或無窮大
     */
    /*
     第一個參數(shù):要轉換成JSON數(shù)據(jù)的OC對象,這里為一個字典
     第二個參數(shù):NSJSONWritingPrettyPrinted對轉換之后的JSON對象進行排版,無意義
     */
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictM options:NSJSONWritingPrettyPrinted error:nil];

    //3.打印查看Data是否有值
    /*
     第一個參數(shù):要轉換為STring的二進制數(shù)據(jù)
     第二個參數(shù):編碼方式,通常采用NSUTF8StringEncoding
     */
    NSString *strM = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",strM);

(3)OC對象和JSON數(shù)據(jù)格式之間的一一對應關系

//OC對象和JSON數(shù)據(jù)之間的一一對應關系
-(void)oCWithJSON
{
    //JSON的各種數(shù)據(jù)格式
    //NSString *test = @"\"wendingding\"";
    //NSString *test = @"true";
    NSString *test = @"{\"name\":\"wendingding\"}";

    //把JSON數(shù)據(jù)->OC對象,以便查看他們之間的一一對應關系
    //注意點:如何被解析的JSON數(shù)據(jù)如果既不是字典也不是數(shù)組(比如是NSString), 那么就必須使用這NSJSONReadingAllowFragments
    id obj = [NSJSONSerialization JSONObjectWithData:[test dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];

    NSLog(@"%@", [obj class]);


    /* JSON數(shù)據(jù)格式和OC對象的一一對應關系
         {} -> 字典
         [] -> 數(shù)組
         "" -> 字符串
         10/10.1 -> NSNumber
         true/false -> NSNumber
         null -> NSNull
     */
}
}
  • 1.3 字典轉模型框架

(1)相關框架

 a.Mantle 需要繼承自MTModel
 b.JSONModel 需要繼承自JSONModel
 c.MJExtension 不需要繼承,無代碼侵入性

(2)自己設計和選擇框架時需要注意的問題

a.侵入性
b.易用性,是否容易上手
c.擴展性,很容易給這個框架增加新的功能

(3)MJExtension框架的簡單使用

//1.把字典數(shù)組轉換為模型數(shù)組
    //使用MJExtension框架進行字典轉模型
        self.videos = [XMGVideo objectArrayWithKeyValuesArray:videoArray];

//2.重命名模型屬性的名稱
//第一種重命名屬性名稱的方法,有一定的代碼侵入性
//設置字典中的id被模型中的ID替換
+(NSDictionary *)replacedKeyFromPropertyName
{
    return @{
             @"ID":@"id"
             };
}

//第二種重命名屬性名稱的方法,代碼侵入性為零
    [XMGVideo setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"ID":@"id"
                 };
    }];

JSONdemo

#import "ViewController.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "VideosItem.h"
#import <MediaPlayer/MediaPlayer.h>
#define baseUrl @"http://120.25.226.186:32812"
@interface ViewController ()
@property(nonatomic,strong)NSMutableArray * videos ;
@end

@implementation ViewController
-(NSMutableArray *)videos
{
    if (_videos==nil) {
        _videos = [NSMutableArray new];
    }
    return _videos;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    /**
     *  模型id替換為ID
     */
    [VideosItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{@"ID":@"id"};
    }];
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        /**
         *  通過字典數(shù)組來創(chuàng)建一個模型數(shù)組
         */
       self.videos = [VideosItem mj_objectArrayWithKeyValuesArray:dict[@"videos"]];
        
        [self.tableView reloadData];
        
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videos.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"videos";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    VideosItem *item = self.videos[indexPath.row];
    cell.textLabel.text = item.name;
    cell.detailTextLabel.text = item.length;
    NSString *imageUrl = [baseUrl stringByAppendingPathComponent:item.image];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"Snip20160225_341"]];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideosItem *item = self.videos[indexPath.row];
    NSString *url = [baseUrl stringByAppendingPathComponent:item.url];
    MPMoviePlayerViewController * vc = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:url]];
    [self presentViewController:vc animated:YES completion:nil];
}
@end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,692評論 19 139
  • JSON介紹 JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。它使得...
    看我的大白眼閱讀 2,544評論 3 9
  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 15,637評論 4 61
  • 我的博客原文地址 在iOS開發(fā)過程中經常需要與服務器進行數(shù)據(jù)通訊,Json就是一種常用的高效簡潔的數(shù)據(jù)格式。 問題...
    zlcode閱讀 1,647評論 0 4
  • 前篇:一個人的環(huán)游中國之行——第一站:黑河(國內最北方) 窗外滴滴答答的雨聲將我從睡夢中叫醒,我關掉恒溫22度的空...
    盛曉明閱讀 852評論 4 3

友情鏈接更多精彩內容