iOS之路15-JSON解析

一: 本地搭建測試服務器php

  1. 打開finder,快捷鍵shift+com+g 進入/etc/apache2目錄web

  2. 顯示隱藏目錄  defaults write com.apple.finder AppleShowAllFiles -bool trueapache

  3. 更改apache2目錄權限爲 "讀與寫"json

  4. 修改httped.conf以前先備份一份, 數組

    (1)修改 DocumentRoot "/Users/用戶名/myweb"  Directory "/Users/用戶名/myweb" ,把已經準備好的json文件放到該目錄下 ,以備測試使用服務器

        (2)添加Indexes, app

            Options Indexes FollowSymLinks Multiviewsiview

            MultiviewsMatch Any測試

        (3)把前面的# 去掉url

            LoadModule php5_module libexec/apache2/libphp5.so

    5.  啓動apache

        sudo apachectl -k start


二: 主要方法 (反序列化的方法)

NSJSONSerialization JSONObjectWithData


三: 核心  把JSON形式的字符串轉換成OC對象

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            if (connectionError) {
                NSLog(@"鏈接錯誤 %@",connectionError);
                return;
            }
            
            // 強制轉換類型
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
                //解析數據   data  JSON形式的字符串
                
                //JSON序列化  把對象轉換成JSON形式的字符串
                //JSON的反序列化      把JSON形式的字符串轉換成OC中的對象
                
                NSError *error;
                
                //解析的JSON字符串,返回的OC對象多是數組或字典
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                if (error) {
                    NSLog(@"解析JSON出錯 %@",error);
                    return;
                }          
                NSLog(@"%@",json);
    
                
            }else{
                NSLog(@"服務器內部錯誤");
            }
        }];
    }
@end
相關文章
相關標籤/搜索