iOS NSDictionary访问JSON值

时间:2017-08-17 13:08:44

标签: ios json nsdictionary

我如何访问“display_name”中的值,假设这是从JSON get请求返回的NSDictionary?

这是我到目前为止所尝试的:

NSString *carName = vehicleListDict[@"response:display_name"]; 
NSString *carName = vehicleListDict[@"display_name"];

{
  "response": [
    {
      "color": null,
      "display_name": "hello",
      "id": 321,
      "option_codes": "MS01,RENA,TM00,DRLH,PF00,BT85,PBCW,RFPO,WT19,IBMB,IDPB,TR00,SU01,SC01,TP01,AU01,CH00,HP00,PA00,PS00,AD02,X020,X025,X001,X003,X007,X011,X013",
      "user_id": 123,
      "vehicle_id": 1234567890,
      "vin": "5YJSA1CN5CFP01657",
      "tokens": [
        "x",
        "x"
      ],
      "state": "online"
    }
  ],
  "count": 1
}

3 个答案:

答案 0 :(得分:2)

在你的回复中你可以看到response包含一个数组if item,所以让我们得到数组:

NSArray *response = vehicleListDict[@"response"];

然后我们可以像:

这样的价值
NSString *displayName = nil;
if (response.count > 0) {
    NSDictionary *vehicle = response[0];
    displayName = vehicle[@"display_name"];
}

答案 1 :(得分:0)

NSDictionary *responseDictionary = json[@"response"][0]; 
NSString *displayName = responseDictionary[@"display_name"];

答案 2 :(得分:0)

假设,结果存储在名为dictResponseData

的字典变量中
NSArray *arrResponse = [dictResponseData objectForKey:@"response"];

for (NSDictionary *dict in arrResponse) {

    //strDisplayName holds the value you want
    NSString *strDisplayName = [dict objectForKey:@"display_name"];
}