OC-开发案例收集

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

2020-08-26  本文已影响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 ""
    }
上一篇下一篇

猜你喜欢

热点阅读