zoukankan      html  css  js  c++  java
  • IOS数据解析之JSON

    JSON解析

    *注  如何将Json数据传到服务器

        // 提交json字符串到服务器
        // 1.创建字典
        NSDictionary *dic = @{
            @"username":@"test",
            @"password":@[@"test1",@"test2"]
        };
        // 2.系统把对象(NSArray,NSDic)转化为json字符串
        NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    1)JSONKit (MRC)

    1>导入JSONKit库

    2>修改ARC   build phase ->compile sources ->选择文件双击添加 -fno-objc-arc

    3>解析

    NSString *urlString = @"https://api.douban.com/v2/book/search?q=s";
    
        [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            // 使用JSONKit 进行json数据解析
            NSDictionary *dic = [data objectFromJSONData];
    }];

    2)系统自带类

     [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            // 系统自带类解析
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }];

    3) JSONModel 

    注意点:

     ItemModel.h

    1.#import "JSONModel.h"

    2.@interface ItemModel : JSONModel

       NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            NSDictionary *dictJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //取出字典里的applications数组
            NSArray *applications = [dictJSON objectForKey:@"applications"];
            for (NSDictionary *dict in applications) {
            // ItemModel继承自JSONModel,只需定义属性
                ItemModel *ietm = [[ItemModel alloc] initWithDictionary:dict error:nil];
                
                NSLog(@"%@
    
    
    ",ietm.toJSONString);
            }
        }];

    结果

  • 相关阅读:
    极大似然估计理解与应用
    逻辑回归理解及代码实现
    《剑指offer》---数值的整数次方
    线性回归理解及代码实现
    二叉搜索树(BST)---python实现
    《剑指offer》---顺时针打印矩阵
    《剑指offer》---二进制中1的个数
    《剑指offer》---输出链表倒数第k个结点
    版本控制-Git服务器搭建和常用命令使用
    hbase伪分布式平台搭建(centos 6.3)
  • 原文地址:https://www.cnblogs.com/3WWanXiang/p/4905453.html
Copyright © 2011-2022 走看看