Swift学习

Swift - JSON转数组,数组转JSON等相关方法

2019-12-16  本文已影响0人  waytheway

//数组转JSON
func arrayToJson(_ array:NSMutableArray)->String{

//首先判断能不能转换
if (!JSONSerialization.isValidJSONObject(array)) {
    //print("is not a valid json object")
    return ""
}

//利用OC的json库转换成OC的NSData,
//如果设置options为NSJSONWritingOptions.PrettyPrinted,则打印格式更好阅读
let data : Data! = try? JSONSerialization.data(withJSONObject: array, options: [])
//NSData转换成NSString打印输出
let str = NSString(data:data, encoding: String.Encoding.utf8.rawValue)
//输出json字符串
return str! as String

}

//OC
-(NSString *)arrayToJson:(NSArray *)array{

NSData * data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];

NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return str;

}

//数组(里面类型为字典)转字符串
func dicArrayToJson(_ dicArray:[Dictionary<String,String>])->String{

//首先判断能不能转换
if (!JSONSerialization.isValidJSONObject(dicArray)) {
    //print("is not a valid json object")
    return ""
}

//利用OC的json库转换成OC的NSData,
//如果设置options为NSJSONWritingOptions.PrettyPrinted,则打印格式更好阅读
let data : Data! = try? JSONSerialization.data(withJSONObject: dicArray, options: [])
//NSData转换成NSString打印输出
let str = NSString(data:data, encoding: String.Encoding.utf8.rawValue)
//输出json字符串
return str! as String

}

/** json 字符串字典*/
func jsonToObject(jsonString:String)->Dictionary<String,NSObject>{

let dic = Dictionary<String,NSObject>()


do{
    
    let data = jsonString.data(using: String.Encoding.utf8)!
    //把NSData对象转换回JSON对象
    let json :Any! = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers)
    
    return json as! Dictionary<String, NSObject>
}catch{
    return dic
}

}

/** json 字符串数组*/
func jsonToArray(jsonString:String)->Array<Dictionary<String, String>>{

let arr = [Dictionary<String,String>()]


do{
    
    let data = jsonString.data(using: String.Encoding.utf8)!
    //把NSData对象转换回JSON对象
    let json : Any! = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers)
    
    return json as! [Dictionary<String, String>]
}catch{
    return arr
}

}

上一篇下一篇

猜你喜欢

热点阅读