//數(shù)組轉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;
}
//數(shù)組(里面類型為字典)轉字符串
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 字符串數(shù)組*/
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
}
}