iOS 字典和json之间的转化

/**

 *  字典转为json

 *

 *  @param dcit 字典类型数据

 *

 *  @return json字符串

 */

- (NSString *)dictToJson:(NSDictionary *)userInf

{

    // isValidJSONObject判断对象是否可以构建json对象

    if (![NSJSONSerialization isValidJSONObject:userInf]) {

        return nil;

    }

    NSError *error;

   // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白,使输出更具可读性。

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInf options:NSJSONWritingPrettyPrinted error:&error];

    NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return json;

}

/**

 *  json字符串转为字典

 *

 *  @param json json字符串

 *

 *  @return 字典类型数据

 */

- (NSDictionary*) jsonToDcit:(NSString*)json

{

    if (!json || json.length == 0) {

        return nil;

    }

    

    NSError *error = nil;

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];

    

    if (error) {

        NSLog(@"jsonToDcit failed: %@", error.description);

    }

 

    return dict;

}

JSONObjectWithData:options:error:方法来进行数据转换,这里的options是一个枚举值

即:

typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {

    NSJSONReadingMutableContainers = (1UL << 0),

     NSJSONReadingMutableLeaves = (1UL << 1),

     NSJSONReadingAllowFragments = (1UL << 2)

} NS_ENUM_AVAILABLE(10_7, 5_0)

 NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。

NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString

NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,

但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串,例如

                            NSString *num=@"32";
			    NSError *error;
			    NSData *createdData = [num dataUsingEncoding:NSUTF8StringEncoding];
			    id response=[NSJSONSerialization JSONObjectWithData:createdData options:NSJSONReadingAllowFragments error:&error];
			    NSLog(@"Response= %@",response);

/**

 *  json data 转为字典

 *

 *  @param json json data

 *

 *  @return 字典类型数据

 */

- (NSDictionary*) jsonDataToDcit:(NSData *)data

{

    if (!data) {

        return nil;

    }

    

    NSError *error = nil;

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

    if (error) {

        NSLog(@"jsonDataToDcit failed: %@", error.description);

    }

    

    return dict;

}















    


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值