JSON处理

来源:互联网 发布:ipad怎么看淘宝直播间 编辑:程序博客网 时间:2024/06/06 03:12
<span style="font-family: Arial, Helvetica, sans-serif;">// 创建JSON对象</span>
- (void)createJsonObj{    NSNumber *age = [NSNumber numberWithInt:25];    NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"麦子",@"name",@"男",@"sex",age,@"age", @"六中",@"school",@"湖南",@"area", nil];        NSDictionary *dicA = [[NSDictionary alloc] initWithObjectsAndKeys:@"小麦子",@"name",@"男",@"sex",age,@"age", @"六中",@"school",@"湖南",@"area", nil];        NSArray *arrayData = [[NSArray alloc] initWithObjects:dic,dicA, nil];        // 字典数据转JSON    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayData options:NSJSONWritingPrettyPrinted error:nil];    // 数据打印    NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];        NSLog(@"%@",str);}// 解析JSON- (void)preJSONData{    NSURL *url = [[NSURL alloc] initWithString:@"http://weather.com.cn/adat/cityinfo/101010100.html"];        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];    NSData *requestData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];    //    NSString *str = [[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding];        NSDictionary  *dic = [NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingMutableLeaves error:nil];        // 对于返回的是数组的时候,就这样。 这个方法返回的是一个id类型    NSArray  *dicArray = [NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingMutableLeaves error:nil];        NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];    for (NSString *str in [weatherDic allKeys]) {        NSLog(@"%@---%@",str,[weatherDic objectForKey:str]);    }        }
0 0
原创粉丝点击