【发布时间】:2014-06-06 01:41:08
【问题描述】:
我很难理解这个问题:
所以我有以下 JSON:
"posts": [
{
"id": 42400,
"type": "post",
"url": "http://dummy.com/noticias/2014/06/senado-promulga-emenda-contra-trabalho-escravo-42400/",
"status": "publish",
"title": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
"title_plain": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
"content": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>",
"excerpt": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>",
"date": "2014-06-05 16:59:55",
"modified": "2014-06-05 17:00:42",
"author": {
"id": 2,
"slug": "author",
"name": "Author",
"first_name": "Author",
"last_name": "",
"nickname": "Author",
"url": "",
"description": ""
},
"thumbnail_images": {
"full": {
"url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo.jpg",
"width": 585,
"height": 390
},
"thumbnail": {
"url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-110x110.jpg",
"width": 110,
"height": 110
},
"medium": {
"url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-230x130.jpg",
"width": 230,
"height": 130
},
"large": {
"url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-585x360.jpg",
"width": 585,
"height": 360
},
"slider-thumb": {
"url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-520x390.jpg",
"width": 520,
"height": 390
}
}
},
这就是我解析这个 JSON 的方式:
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil ) {
*error = localError;
return nil;
}
NSMutableArray *posts = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:@"posts"];
for (NSDictionary *postDic in results) {
Data *data = [[Data alloc] init];
for (NSString *key in postDic) {
if ([data respondsToSelector:NSSelectorFromString(key)]) {
[data setValue:[postDic valueForKey:key] forKey:key];
}
}
[posts addObject:data];
}
return posts;
我似乎无法理解的是如何访问“thumbnail_images”中的第一个值,即“full”,然后获取它的“url”值。
【问题讨论】:
-
您在 JSON 列表中省略了最初的
{,它标志着“对象”的开始。观察 JSON 字符串中的所有字符很重要。 -
至于怎么解析,像洋葱一样剥,一层一层。你有外部字典,然后是一个数组,然后是包含更多字典的内部字典。仔细观察筑巢。你这样做的方式只对相当“扁平”的 JSON 有效,而上面的不是。
-
@HotLicks 您是否建议在 Data.h 模型中存储这些项目的不同方法?是的,我省略了开头的 { there sorry
-
首先,大约有一半的时间没有令人信服的理由不简单地将数据保留为已解析的数组和字典。它们非常简单且访问起来相当有效。
-
如何分离和可视化存储在 *data 中的数据:for (NSString *key in postDic) { if ([data respondsToSelector:NSSelectorFromString(key)]) { [data setValue:[ postDic valueForKey:key] forKey:key]; } }
标签: ios objective-c json nsdictionary