美文网首页OC-开发案例收集
iOS开发中字典和字符串的相互转换

iOS开发中字典和字符串的相互转换

作者: 晴川历历汉阳树丶 | 来源:发表于2020-08-26 13:52 被阅读0次

    OC:

    1.字符串转字典

    NSString * jsonString = @"";
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
      //解析出错
    }
    

    2.字典转字符串

    NSError *parseError;
    Data *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    if (parseError) {
      //解析出错
    }
    NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    

    Swift

      
         //将数组/字典 转化为字符串
        class func getJSONStringFromData(obj:Any) -> String {
            
            if (!JSONSerialization.isValidJSONObject(obj)) {
                print("无法解析出JSONString")
                return ""
            }
            
            if let data : NSData = try? JSONSerialization.data(withJSONObject: obj, options: []) as NSData? {
                if let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) {
                    return JSONString as String
                }
            }
            return ""
        }
    
        //将字符串转化为 数组/字典
        class func getArrayOrDicFromJSONString(jsonString:String) -> Any {
            
            let jsonData:Data = jsonString.data(using: .utf8)!
            
            //可能是字典也可能是数组,再转换类型就好了
            if let info = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
                return info
            }
            return ""
        }
    

    相关文章

      网友评论

        本文标题:iOS开发中字典和字符串的相互转换

        本文链接:https://www.haomeiwen.com/subject/uilzjktx.html