iOS 字典与字符串互相转换

Swift:

Swift3 JSON字符串和字典互转(JSON字符串转字典和字典转JSON字符串)

http://www.cnblogs.com/yajunLi/p/6549859.html


/// JSONString转换为字典

///

/// - Parameter jsonString: <#jsonString description#>

/// - Returns: <#return value description#>

func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{

let jsonData:Data = jsonString.data(using: .utf8)!

let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)

if dict != nil {

return dict as! NSDictionary

}

return NSDictionary()

}

/**

字典转换为JSONString

- parameter dictionary: 字典参数

- returns: JSONString

*/

func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {

if (!JSONSerialization.isValidJSONObject(dictionary)) {

print("无法解析出JSONString")

return ""

}

let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!

let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)

return JSONString! as String

}


Object-C:

- (void)viewDidLoad {

[super viewDidLoad];

NSDictionary *dict = @{@"aaa":@"11",@"bb":@"22",@"cc":@"33"};

NSString *str = [self dictionaryToJson:dict];

NSDictionary *dict1 = [self dictionaryWithJsonString:str];

NSLog(@"%@",str);

NSLog(@"%@",dict1);

}

/*!

* @brief 把格式化的JSON格式的字符串转换成字典

* @param jsonString JSON格式的字符串

* @return 返回字典

*/

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {

if (jsonString == nil) {

return nil;

}

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *err;

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

options:NSJSONReadingMutableContainers

error:&err];

if(err) {

NSLog(@"json解析失败:%@",err);

return nil;

}

return dic;

}

//词典转换为字符串

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{

NSError *parseError = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

你可能感兴趣的:(iOS 字典与字符串互相转换)