ios - 在ios中将json转换成字典

标签 ios iphone json dictionary

我正在尝试将此 json 数据转换为字典,但我无法帮助我。

 {
     "homeMobileCountryCode": 310,
     "homeMobileNetworkCode": 260,
     "radioType": "gsm",
     "carrier": "T-Mobile",
     "cellTowers": [
      {
       "cellId": 39627456,
       "locationAreaCode": 40495,
       "mobileCountryCode": 310,
       "mobileNetworkCode": 260,
       "age": 0,
       "signalStrength": -95
      }
     ],
     "wifiAccessPoints": [
      {
       "macAddress": "01:23:45:67:89:AB",
       "signalStrength": 8,
       "age": 0,
       "signalToNoiseRatio": -65,
       "channel": 8
      },
      {
       "macAddress": "01:23:45:67:89:AC",
       "signalStrength": 4,
       "age": 0
      }
     ]
    }

我只知道像这样从字典转换成JSON

NSMutableDictionary * location = [[NSMutableDictionary alloc]init];
    [location setValue:mobileCountryCode forKey:@"mobileCountryCode"];
    [location setValue:mobileNetworkCode forKey:@"mobileNetworkCode"];
    [location setValue:cellId forKey:@"cellId"];
    [location setValue:locationAreaCode forKey:@"locationAreaCode"]; 


 NSData *data = [NSJSONSerialization dataWithJSONObject:requestbodyInputDict options:NSUTF8StringEncoding error:nil];
                NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"jsonString.....%@",jsonString);
                NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

所以请帮助我如何扭转这个过程如何处理这个问题。

最佳答案

只需检查这段代码。它会将您的 json 转换为 NSdictionary

   NSString *jsonString = @"{ \"homeMobileCountryCode\": 310, \"homeMobileNetworkCode\": 260, \"radioType\": \"gsm\", \"carrier\": \"T-Mobile\", \"cellTowers\": [ { \"cellId\": 39627456, \"locationAreaCode\": 40495, \"mobileCountryCode\": 310, \"mobileNetworkCode\": 260, \"age\": 0, \"signalStrength\": -95 } ], \"wifiAccessPoints\": [ { \"macAddress\": \"01:23:45:67:89:AB\", \"signalStrength\": 8, \"age\": 0, \"signalToNoiseRatio\": -65, \"channel\": 8 } ] }";

    NSError *jsonError;
    NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&jsonError];

使用String replace方法将"替换为\"就可以了

关于ios - 在ios中将json转换成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429157/

相关文章:

iphone - uitableview 的 Storyboard错误

iphone - 我如何通过xcode搜索iphone中的所有声音文件

java - 如何在 iPhone 中查看 Google 网络应用程序

json - 返回多个键值对的 json,而不是单对键值 json 的列表

javascript - 如何在 Node.js 中从 JSON 文件创建对象

ios - 为什么我不能使用 "List"作为 UITableViewController 子类的类名?

ios - 从 appdelegate 传递一个全局变量返回 null

iphone - 无限旋转图片背景UIImageView

javascript - 使用 Ember-data 序列化非常规 JSON

ios - tableview 滚动得到错误的最后一个单元格