加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

NSJSONSerialization使用——json格式字符串与dict字典的相互转

发布时间:2020-12-16 18:58:01 所属栏目:百科 来源:网络整理
导读:json格式字符串与dict字典的相互转换,可以使用系统自带的NSJSONSerialization类。 当然也可以使用第三框架进行操作,如JSONKit(https://github.com/johnezang/JSONKit)。 // dict字典转json字符串- (NSString *)jsonStringWithDictionary:(NSDictionary *

json格式字符串与dict字典的相互转换,可以使用系统自带的NSJSONSerialization类。

当然也可以使用第三框架进行操作,如JSONKit(https://github.com/johnezang/JSONKit)。


// dict字典转json字符串
- (NSString *)jsonStringWithDictionary:(NSDictionary *)dict
{
    if (dict && 0 != dict.count)
    {
        NSError *error = nil;
        // NSJSONWritingOptions 是"NSJSONWritingPrettyPrinted"的话有换位符n;是"0"的话没有换位符n。
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
    
    return nil;
}

// json字符串转dict字典
- (NSDictionary *)jsonDictWithString:(NSString *)string
{
    if (string && 0 != string.length)
    {
        NSError *error;
        NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        
        if (error)
        {
            NSLog(@"json解析失败:%@",error);
            return nil;
        }
        
        return jsonDict;
    }
    
    return nil;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读