zoukankan      html  css  js  c++  java
  • JSON解析

    [ ]==JSONArray -->Json数组 --> OC NSArray

    {} ==JSONObject -->Json对象 -->OC NSDictionary

    -(NSArray*)productArray{

        if(_productArray == nil){

            //1.加载json数据

            //2.json中的数据转换为模型

            

              //2.1获取json文件的全路径

            NSString *path =[[NSBundle mainBundle]pathForResource:@"product.json" ofType:nil];

              //2.2根据全路径加载json文件到NSData

            NSData *data = [NSData dataWithContentsOfFile:path];

              //2.3 将加载进来的NSdata数据转换为OC对象

            NSArray *dictArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers  error:nil];

            // 3.将转换后的数据传递给products

            NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictArray.count];

            for (NSDictionary *dict in dictArray) {

                NJProduct *product = [NJProduct NJProductWithDict:dict];

                [models addObject:product];

            }

            _productArray = models;

        }

        return _productArray;

        

    }

    iOS中JSON数据解析

    官方为我们提供的解析JSON数据的类是NSJSONSerialization,首先我们先来看下这个类的几个方法:

    + (BOOL)isValidJSONObject:(id)obj;

    判断一个数据对象是否可以转化为JSON数据

    + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

    将JSON数据写为NSData数据,其中opt参数的枚举如下,这个参数可以设置,也可以不设置,如果设置,则会输出视觉美观的JSON数据,否则输出紧凑的JSON数据。

    typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
        NSJSONWritingPrettyPrinted = (1UL << 0)
    }

     + (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

    这个方法是解析中数据的核心方法,data是JSON数据对象,可以设置一个opt参数,具体用法如下:

    typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {     

        //将解析的数组和字典设置为可变对象 (将来解析出来的是NSArray或NSDictionary)    

        NSJSONReadingMutableContainers = (1UL << 0),     

       //将解析数据的子节点创建为可变字符串对象     

       NSJSONReadingMutableLeaves = (1UL << 1),     

       //允许解析对象的最上层不是字典或者数组     

       NSJSONReadingAllowFragments = (1UL << 2)

    }

    + (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error;

    将JSON数据写入到输出流,返回的是写入流的字节数

    + (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError**)error;

    从输入流读取JSON数据

  • 相关阅读:
    vue学习03 v-html
    [spring guides]网关入门
    记一次公司mssql server密码频繁被改的事件
    重构 maixpy 的 board_info + config.json 从而自适应硬件版型。
    介绍 MaixUI 系列(一)如何食用?
    (旧文)在 micropython / esp-at / arduino 中实现 软串口(software-serial) 的参考
    以优化 MaixPy 的启动速度为例,说说 K210 的双核使用及原子操作。
    我是如何在 Win + VSCode 上开发 Keil for GD32 实现 I2C 从机的游戏机手柄。
    为 MaixPy 加入软 SPI 接口(移植 MicroPython 的 SPI)
    为 MaixPy 加入软 I2C 接口(移植 MicroPython 的 I2C)
  • 原文地址:https://www.cnblogs.com/seeworld/p/6096279.html
Copyright © 2011-2022 走看看