隐藏json到ios中的字典

时间:2016-02-16 09:54:26

标签: 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
      }
     ]
    }

我知道只能像这样从Dictionary转换为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];

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

2 个答案:

答案 0 :(得分:2)

请检查此代码。它会将你的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];

使用字符串替换方法替换“与\”它将起作用

答案 1 :(得分:0)

你正在做的是你直接访问“mobileCountryCode”,“mobileNetworkCode”等等...这是json数组“cellTowers”的元素所以如果你想要这些值你可以先得到一个“cellTowers”数组那你去...