解析JSON读取各种字典

Posted

技术标签:

【中文标题】解析JSON读取各种字典【英文标题】:Parsing JSON read the various dictionaries 【发布时间】:2014-08-10 21:12:09 【问题描述】:

我是 json 新手,遇到了一些困难,我正在尝试解析以下 json。

但我无法阅读各种字典“项目”。

["project": 
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"user": 
    "id": 1,
    "name": "Blake Watters",
    "email": "blake@twotoasters.com"
,
"tasks": [
    "id": 1, "name": "Identify samples to write", "assigned_user_id": 1,
    "id": 2, "name": "Write the code", "assigned_user_id": 1,
    "id": 3, "name": "Push to Github", "assigned_user_id": 1,
    "id": 4, "name": "Update the mailing list", "assigned_user_id": 1
],
"project": 
"id": 456,
"name": "Document Object Mapper",
"description": "The object mapper could really use some docs!",
"user": 
    "id": 2,
    "name": "Jeremy Ellison",
    "email": "jeremy@twotoasters.com"
,
"tasks": [
    "id": 5, "name": "Mark up methods with Doxygen markup", "assigned_user_id": 2,
    "id": 6, "name": "Generate docs and review formatting", "assigned_user_id": 2,
    "id": 7, "name": "Review docs for accuracy and completeness", "assigned_user_id": 1,
    "id": 8, "name": "Publish to Github", "assigned_user_id": 2
]]

我正在使用 AFNETWorking,这是我的代码:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
for (NSDictionary *json in [responseObject objectForKey:@"project"])
        simProjects *proj = [[simProjects alloc] init];
        proj.description = [json objectForKey: @"description"];

【问题讨论】:

你收到的 JSON 绝对是一个数组。它是一个 NSDictionary 的数组,每个 NSDictionary 都有一个键“项目”。 【参考方案1】:

如前所述,您确实有一系列字典。你想要:

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    NSArray *projects = responseObject;
    for (NSDictionary *data in projects) 
        NSDictionary *project = data[@"project"];
        simProjects *proj = [[simProjects alloc] init];
        proj.description = project[@"description"];
    

【讨论】:

以上是关于解析JSON读取各种字典的主要内容,如果未能解决你的问题,请参考以下文章

pandas DataFrame 使用 to_json() 到字典列表

教你一招:让你的json文件更好看

IOS--JSON数据解析成字典

json解析错误怎么办?

如何解析 JSON 字典

解析 JSON 字典/数组