如何从此 json 数据中获取键和值?
Posted
技术标签:
【中文标题】如何从此 json 数据中获取键和值?【英文标题】:How to fetch keys and values from this json data? 【发布时间】:2015-10-24 04:18:36 【问题描述】:
"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】:你做错了。
要将 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];
【讨论】:
以上是关于如何从此 json 数据中获取键和值?的主要内容,如果未能解决你的问题,请参考以下文章
如何在使用 Scala-Play Json 框架解析 Json 时获取键和值?
如何在iOS swift的tableview中使用json响应中的键和值?