iOS学习:JSON解析

本文介绍iOS平台上的JSON解析方法,重点讲解苹果官方提供的NSJSONSerialization类的使用方式,包括创建和解析JSON对象的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON是一种轻量级的数据交换格式。iOS平台上进行JSON解析,有很多第三方的开源项目,比如JSONKit,SBJon等。从iOS5.0以后,苹果推出了自带的JSON解决方案NSJSONSerialization。NSJSONSerialization 可以将JSON数据转换为Foundation (NSDictionary和NSArray)对象Coco Foundation(NSDictionary和NSArray)对象转换为JSON数据,还可以调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据。

1.     使用NSJSONSerialization的条件:

顶层对象必须是NSArray或者NSDictionary

所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例

所有NSDictionary的key必须是NSString类型

数字对象不能是非数值或无穷

2.     NSJSONSerialization使用:

Creating a JSON Object

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

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

Creating JSON Data

+ (NSData *)dataWithJSONObject:(id)objoptions:(NSJSONWritingOptions)opt
            error:(NSError **)error

+ (NSInteger)writeJSONObject:(id)objtoStream:(NSOutputStream *)stream
           options:(NSJSONWritingOptions)opterror:(NSError **)error

+ (BOOL)isValidJSONObject:(id)obj

Constants

enum{

   NSJSONReadingMutableContainers =(1UL <<0),

   NSJSONReadingMutableLeaves =(1UL <<1),

   NSJSONReadingAllowFragments =(1UL <<2)

};

typedefNSUInteger NSJSONReadingOptions;

enum{     

NSJSONWritingPrettyPrinted =(1UL <<0)};

typedefNSUInteger NSJSONWritingOptions;

    //创建JSON
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"name",@"name",@"age",@"age",@"sex",@"sex", nil];
    // isValidJSONObject判断对象是否可以构建成json对象
    if ([NSJSONSerialization isValidJSONObject:dic]){
        NSError *error;
        // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白,使输出更具可读性。
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    
     //解析JSON
    // define error
    NSError *error;
    // define url request
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString: @"http://m.weather.com.cn/data/101010100.html"]];
    // get reponse data from url request
    NSData *dataResponse = [NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: nil];
    // use nsjson transfer data to dictionary
    NSDictionary *dictionaryWeather = [NSJSONSerialization JSONObjectWithData: dataResponse options: NSJSONReadingMutableLeaves error: &error];
    // get weather info from weather dictionary
    NSDictionary *dictionaryWeatherInfo = [dictionaryWeather objectForKey: @"weatherinfo"];
    // output weather of today
    NSLog(@"今天是 %@  %@  %@  的天气状况是:%@  %@ ", [dictionaryWeatherInfo objectForKey: @"date_y"], [dictionaryWeatherInfo objectForKey: @"week"],[dictionaryWeatherInfo objectForKey: @"city"], [dictionaryWeatherInfo objectForKey: @"weather1"], [dictionaryWeatherInfo objectForKey: @"temp1"]);
    // output
    NSLog(@"Weather字典里面的内容为--》%@", dictionaryWeather);

    /*
    {
        "weatherinfo": {
            "city": "北京",
            "city_en": "beijing",
            "date_y": "2014年3月4日",
            "date": "",
            "week": "星期二",
            "fchh": "11",
            "cityid": "101010100",
            "temp1": "8℃~-3℃",
            "temp2": "8℃~-3℃",
            "temp3": "7℃~-3℃",
            "temp4": "8℃~-1℃",
            "temp5": "10℃~1℃",
            "temp6": "10℃~2℃",
            "tempF1": "46.4℉~26.6℉",
            "tempF2": "46.4℉~26.6℉",
            "tempF3": "44.6℉~26.6℉",
            "tempF4": "46.4℉~30.2℉",
            "tempF5": "50℉~33.8℉",
            "tempF6": "50℉~35.6℉",
            "weather1": "晴",
            "weather2": "晴",
            "weather3": "晴",
            "weather4": "晴转多云",
            "weather5": "多云",
            "weather6": "多云",
            "img1": "0",
            "img2": "99",
            "img3": "0",
            "img4": "99",
            "img5": "0",
            "img6": "99",
            "img7": "0",
            "img8": "1",
            "img9": "1",
            "img10": "99",
            "img11": "1",
            "img12": "99",
            "img_single": "0",
            "img_title1": "晴",
            "img_title2": "晴",
            "img_title3": "晴",
            "img_title4": "晴",
            "img_title5": "晴",
            "img_title6": "晴",
            "img_title7": "晴",
            "img_title8": "多云",
            "img_title9": "多云",
            "img_title10": "多云",
            "img_title11": "多云",
            "img_title12": "多云",
            "img_title_single": "晴",
            "wind1": "北风4-5级转微风",
            "wind2": "微风",
            "wind3": "微风",
            "wind4": "微风",
            "wind5": "微风",
            "wind6": "微风",
            "fx1": "北风",
            "fx2": "微风",
            "fl1": "4-5级转小于3级",
            "fl2": "小于3级",
            "fl3": "小于3级",
            "fl4": "小于3级",
            "fl5": "小于3级",
            "fl6": "小于3级",
            "index": "寒冷",
            "index_d": "天气寒冷,建议着厚羽绒服、毛皮大衣加厚毛衣等隆冬服装。年老体弱者尤其要注意保暖防冻。",
            "index48": "冷",
            "index48_d": "天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。",
            "index_uv": "中等",
            "index48_uv": "中等",
            "index_xc": "较适宜",
            "index_tr": "一般",
            "index_co": "较舒适",
            "st1": "7",
            "st2": "-3",
            "st3": "8",
            "st4": "0",
            "st5": "7",
            "st6": "-1",
            "index_cl": "较不宜",
            "index_ls": "基本适宜",
            "index_ag": "易发"
        }
    }*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值