json

/*有的json代码格式比较混乱,可以使用此http://www.bejson.com/网站来进行JSON格式化校验(点击打开链接)。此网站不仅可以检测Json代码中的错误,而且可以以视图形式显示json中的数据内容,很是方便。

 IOS5开始,APPLE提供了对json的原生支持(NSJSONSerialization),但是为了兼容以前的ios版本,可以使用第三方库来解析Json

 json的格式

 JSON建构有两种结构:

   1. “名称/对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),记录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 associative array)。

   2.值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。*/

//第三方类库解析json

- (IBAction)SBJsonPress:(id)sender

{

    NSURL *url = [NSURLURLWithString:@"http://m.weather.com.cn/data/101180701.html"];

    NSError *error = nil;

    NSString *jsonString = [NSStringstringWithContentsOfURL:url encoding:NSUTF8StringEncodingerror:&error];

    SBJsonParser *parser = [[SBJsonParseralloc] init];

    NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];

    NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];

    self.testView.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];

}

//IOS5之后自带的json

- (IBAction)IOSJsonPress:(id)sender

{

    //创建网络请求,地址是气象网

    NSURLRequest *URLRequest = [[NSURLRequestalloc]initWithURL:[NSURLURLWithString:@"http://m.weather.com.cn/data/101110101.html"]];

    NSError *error = nil;

    NSData *jsonData = [NSURLConnectionsendSynchronousRequest:URLRequest returningResponse:nilerror:&error];

    //NSJSONSerializationresponse中解析出数据放到id类型中

    id jsonObject = [NSJSONSerializationJSONObjectWithData:jsonData options:NSJSONReadingAllowFragmentserror:&error];

    if (jsonObject != nil && error == nil)

    {

        //判断是否为字典

        if ([jsonObject isKindOfClass:[NSDictionary class]])

        {

            //NSJSONSerializationresponse中解析出数据放到id类型中

            NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:jsonData options:NSJSONReadingAllowFragmentserror:&error];

            /*typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {

             NSJSONReadingMutableContainers = (1UL << 0),//返回的对象是可变对象

             NSJSONReadingMutableLeaves = (1UL << 1),//返回可变字符串对象

             NSJSONReadingAllowFragments = (1UL << 2)//返回的对象是不可变对象

             };*/

            NSLog(@"天气信息为:%@",dic);

            //因为返回的Json文件有两层,取第二层内容放到字典中去

            NSDictionary *info = [dic objectForKey:@"weatherinfo"];

            NSString *text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@",[info objectForKey:@"date_y"], [info objectForKey:@"week"],

                              [info objectForKey:@"city"],

                              [info objectForKey:@"weather1"],

                              [info objectForKey:@"temp1"]];

            NSLog(@"%@",text);

        }

    }

    

    else if ([jsonData length] == 0 && error == nil)

    {

        NSLog(@"No data was returned after serialization.");

    }

    else if (error != nil)

    {

        NSLog(@"An error happened = %@", error);

    }

}

//封装成json格式

- (void)encapsulation

{

    NSDictionary *dic = [[NSDictionaryalloc]initWithObjectsAndKeys:@"二狗",@"key1",@"三狗",@"key2",@"四狗",@"key3", nil];

    //封装成json格式

    NSError *error = nil;

    NSData *jsonData = [NSJSONSerializationdataWithJSONObject:dic options:NSJSONWritingPrettyPrintederror:&error];

    //NSJSONWritingPrettyPrinted 生成的json数据格式化输出,不设置则生成一行

    if ([jsonData length] > 0 && error == nil) {

        NSLog(@"jsonData:%@",jsonData);

    }

    else

    {

        NSLog(@"error:%@",error);

    }

}