Swift:
Swift3 JSON字符串和字典互轉(zhuǎn)(JSON字符串轉(zhuǎn)字典和字典轉(zhuǎn)JSON字符串)
http://www.cnblogs.com/yajunLi/p/6549859.html
/// JSONString轉(zhuǎn)換為字典
///
/// - 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()
}
/**
字典轉(zhuǎn)換為JSONString
- parameter dictionary: 字典參數(shù)
- returns: JSONString
*/
func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
if (!JSONSerialization.isValidJSONObject(dictionary)) {
print("無(wú)法解析出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格式的字符串轉(zhuǎn)換成字典
* @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;
}
//詞典轉(zhuǎn)換為字符串
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}