iOS NSDictionary 访问 JSON 值

iOS NSDictionary accessing a JSON value

如何访问 "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
}
NSDictionary *responseDictionary = json[@"response"][0]; 
NSString *displayName = responseDictionary[@"display_name"];

在您的响应中,您可以看到 response 包含一个数组 if item,所以让我们获取数组:

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

然后我们可以这样取值:

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

假设,结果存储在名为 dictResponseData 的字典变量中

NSArray *arrResponse = [dictResponseData objectForKey:@"response"];

for (NSDictionary *dict in arrResponse) {

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