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

来源:互联网 发布:程序员的自我修养 书签 编辑:程序博客网 时间:2024/05/18 01:03
// 字典转换成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格式的字符串,即使强转也是错误的。

1 0
原创粉丝点击