如何从这个json数据中获取键和值?

时间:2015-10-24 04:18:36

标签: ios objective-c json ios8 nsdictionary

{
  "languages": "de-AT,hr,hu,sl",
  "distance": "0",
  "countryCode": "AT",
  "countryName": "Austria"
}

NSDictionary *lan = [NSDictionary dictionaryWithObjectAndKeys:languages,@"lan",nil];
[lan setObject:@"de-AT"ofKey:@"languages"];
[lan setObject:@"hr"ofKey:@"languages"];
[lan setObject:@"hu"ofKey:@"languages"];
[lan setObject:@"sl"ofKey:@"languages"];

NSDictionary *dist = [NSDictionary dictionaryWithObjectAndKeys:@"0",@"distance",nil];

NSDictionary *code= [NSDictionary dictionaryWithObjectAndKeys:@"AT",@"countryCode",nil];

NSDictionary *code= [NSDictionary dictionaryWithObjectAndKeys:@"Austria",@"countryName",nil];

我上面这样做,可能我会错或正确,请发表您的建议,谢谢

1 个答案:

答案 0 :(得分:1)

你做错了。 要将JSON转换为NSDictionary,您应该使用NSJSONSerialization

    /// data = {
    //    "languages": "de-AT,hr,hu,sl",
    //    "distance": "0",
    //    "countryCode": "AT",
    //    "countryName": "Austria"
    //  }
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSString * countryName = dictionary[@"countryName"]; // get countryNAme

用于创建像data

这样的NSDictionary
NSDictionary *dist = [NSDictionary dictionaryWithObjectAndKeys:
                      @"de-AT,hr,hu,sl",@"languages",
                      @"0",@"countryCode"
                      @"AT",@"countryCode"
                      @"Austria",@"countryName"
                       nil];