您的位置:首页 > Web前端 > JavaScript

字典对象与Json字符串相互转换

2017-02-24 10:33 393 查看
// 字典转换成Json字符串
NSDictionary * testDict = @{@"hid":@"1",
@"cut_price":@"2",
@"cut_num":@"3",
@"goods_id":@"4",
@"pool_id":@"5"};
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:testDict options:NSJSONWritingPrettyPrinted error:&error];
NSString * jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// 将json字符串转换成字典
NSData * getJsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];

//打印出来的字典的类型Printing description of editDic:                       {    aAddTime = "2015-07-21 15:02:10";    aAddress = "\U5728\U4e8e\U5979iyyyu";    aAddressType = 0;    aCityId = 3764;    aCityName = "\U4e0a\U6d77\U5e02";    aConstruction = "";    aCountyId = 4138;    aCountyName = "\U9ec4\U6d66\U533a";    aId = 3206;    aIsDefault = 1;    aMobilePhone = 15225632580;    aPhone = "";    aProfileAccountId = 100000032954;    aProvinceId = 3638;    aProvinceName = "\U4e0a\U6d77";    aRealName = "\U534e\U4e1c";    aUpdateTime = "2015-07-21 15:02:10";}

转成要上送的 字符串  (很明显,key都是要带引号的) Printing description of addressStr:{  "aId" : 3206,  "aCityId" : 3764,  "aProvinceName" : "上海",  "aUpdateTime" : "2015-07-21 15:02:10",  "aAddTime" : "2015-07-21 15:02:10",  "aAddressType" : 0,  "aIsDefault" : true,  "aMobilePhone" : "15225632580",  "aPhone" : "",  "aConstruction" : "",  "aRealName" : "华东",  "aProfileAccountId" : 100000032954,  "aCountyId" : 4138,  "aAddress" : "在于她iyyyu",  "aProvinceId" : 3638,  "aCityName" : "上海市",  "aCountyName" : "黄浦区"}


一般的字符串并不能与字典进行转换,,必须是json格式的字符串,如:@“{name = @"成岗", gender = "男"}"; json字符串的小demo格式如下: NSString *jsonString = @“{name = @"成岗", gender = "男"}";要知道字符串和字典的格式本不相同,如果是非son格式的字符串,即使强转也是错误的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: