JSON解析代码

方法1是JSON转OC对象

方法2是OC对象转JSON 以下是示例代码

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self OCtoJSON];
}


-(void)JSONToOC
{
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        
        
        /*
         参数1:JSON的二进制数据
         参数2:
         参数3:错误信息
         
         
         NSJSONReadingMutableContainers = (1UL << 0),   可变的字典和数组
         NSJSONReadingMutableLeaves = (1UL << 1),       内部所有的字符串都是可变的(ios7之后一般不用)
         NSJSONReadingAllowFragments = (1UL << 2)       既不是字典也不是数组,则必须使用该枚举值
         
         */
        
        
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSLog(@"%@",dict[@"error"]);
    }];
}

-(void)OCtoJSON
{
    
    
    //不是所有的OC对象都能转换成JSON
    //可以用这个方法 判断:[NSJSONSerialization isValidJSONObject:<#(nonnull id)#>]
    NSDictionary *dict =@{
        @"name":@"Spencer",
        @"age":@3
    };
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    
    
    
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值