美文网首页
iOS的json字符串与数组和字典之间的转换

iOS的json字符串与数组和字典之间的转换

作者: 肉肉要次肉 | 来源:发表于2017-07-11 09:56 被阅读46次

    //把json字符串转化成数组或者字典

    +(id)parseJSONStringToNSDictionary:(NSString *)JSONString {

    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;

    id jsonObject = [NSJSONSerialization

    JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments

    error:&error];

    if (jsonObject != nil && error == nil){

    NSLog(@"反序列化成功...");

    if ([jsonObject isKindOfClass:[NSDictionary class]]){

    NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;

    NSLog(@"反序列化后的dictionary数据 = %@", deserializedDictionary);

    return deserializedDictionary;

    }

    else if ([jsonObject isKindOfClass:[NSArray class]]){

    NSArray *deserializedArray = (NSArray *)jsonObject;

    NSLog(@"反序列化json后的数组 = %@", deserializedArray);

    return deserializedArray;

    }else {

    return nil;

    }

    }else{

    NSLog(@"%@", error);

    NSLog(@"反序列化时发生一个错误");

    return nil;

    }

    }

    //返回的数据NSData转json,然后解析

    #pragma mark -- AES 解密(用户密钥)--

    NSString *decryptedText = [AESCipher decryptAES:encodedString key:[defaults objectForKey:@"userPriKey"]];

    NSLog(@"浏览历史data解密:%@",decryptedText);

    、、、、、、、、、、、、、、、、、

    NSData *data = [decryptedText dataUsingEncoding:NSUTF8StringEncoding];

    id dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];

    、、、、、、、、、、、、、、、、、、、、

    HistoryViewController *historyVC = [[HistoryViewController alloc]init];

    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:historyVC];

    historyVC.dataArr = dict;

    NSLog(@"转码后的数组%@",dict);

    、、、、、、、、、、、、、、、、、、、

    NSMutableArray *topLevelArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    for (NSDictionary *dic in topLevelArray) {

    historyVC.hisId = [NSString stringWithFormat:@"%@",dic[@"vId"]] ;

    NSLog(@"转码后的hisId:%@",dic[@"vId"]);

    }

    //字典转字符串:

    NSDictionary *messageDic = [NSDictionary dictionaryWithObjectsAndKeys:self.placeTF.text,@"cityFrom",@"",@"destination",@"2017-02",@"depDate",self.peopleTF.text,@"pNum",self.dayTF.text,@"dNum",@"",@"hotel",@"",@"tType",self.OtherTextView.text,@"oInfo",self.budgetTF.text,@"budget",@"0",@"isAbout", nil];

    NSLog(@"所有信息%@",messageDic);

    NSDictionary *dic = messageDic;

    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];

    NSString *messageStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"字典转成字符串messageStr:%@",messageStr);

    相关文章

      网友评论

          本文标题:iOS的json字符串与数组和字典之间的转换

          本文链接:https://www.haomeiwen.com/subject/dmpphxtx.html