zoukankan      html  css  js  c++  java
  • IOS中json的解析

    发现IOS自带的json解析方案NSJSONSerialization还是不错的,方便。用法如下:

     NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",@"value3",@"key3", 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);
        }

     

     

    数据解析:

    NSError *error;
        //加载一个NSURL对象
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101120101.html"]];
        //将请求的url数据放到NSData对象中
        NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
        NSString *text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
        NSLog(@"weatherInfo:%@", text );

     

  • 相关阅读:
    Linux下查看文件内容的命令
    windows下vmware配置nat网络
    xshell连接linux
    django 常见过滤器
    Django模板语言中的自定义方法filter过滤器实现web网页的瀑布流
    关于python开发CRM系统
    关于django form验证是否用户名已存在
    Django model 中的 class Meta 详解
    ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 45, found 43. Created with MySQL 5
    并发编程之线程池
  • 原文地址:https://www.cnblogs.com/xzhios/p/4365694.html
Copyright © 2011-2022 走看看