如何实现 JSON 解析代码以获取对 NSArray 的响应?

Posted

技术标签:

【中文标题】如何实现 JSON 解析代码以获取对 NSArray 的响应?【英文标题】:how to implement code for JSON parsing getting response into the NSArray? 【发布时间】:2012-06-04 08:59:50 【问题描述】:

iphone 代码如何获取数组中的响应?这里我需要存储内容“Id值”、“LastUpdated值”和“Title”这三个值需要存储在3个不同的数组中怎么可能?

回复如下:

[
    
        "Contents": [
            
                "Id": 381,
                "LastUpdated": "/Date(1338347251003+0000)/",
                "Title": "Forrester Study - Total Economic Impact of Lync",
                "Url": "http://infra2apps.blob.core.windows.net/eventapp/Forrester Study - Total Economic Impact of Lync_booth1.pdf"
            
        ],
        "Id": 1,
        "ImageUrl": "http://infra2apps.blob.core.windows.net/eventapp/Lync.png",
        "Name": "Unified Communications & Collaborations",
        "Sessions": [
            
                "Description": "Microsoft Lync delivers Unified Communications to help people connect in new ways, anytime, anywhere.  Learn how HP and Microsoft are helping customers transform their business infrastructure and gain greater productivity by making every communication an interaction that is more collaborative and engaging.",
                "EndDate": "/Date(1338922800000+0000)/",
                "FriendlyName": "TB3257",
                "Id": 1,
                "Location": "TBD",
                "Speakers": [
                    
                        "Company": "Microsoft",
                        "Email": "ashimas@microsoft.com",
                        "Name": "Ashima Singhal",
                        "Title": "Group Marketing Manager, Lync"
                    ,
                    
                        "Company": "HP",
                        "Email": "dragana.beara@hp.com",
                        "Name": "Dragana Beara",
                        "Title": "HP"
                    
                ],
                "StartDate": "/Date(1338920100000+0000)/",
                "Title": "Connecting People in New Ways with Microsoft Lync"
            
        ]
    ,
    
        "Contents": [
            
                "Id": 385,
                "LastUpdated": "/Date(1338347251143+0000)/",
                "Title": "Windows 8 Consumer Preview - Product Guide - Business",
                "Url": "http://infra2apps.blob.core.windows.net/eventapp/Windows 8 Consumer Preview - Product Guide - Business_booth2.pdf"
            ,
            
                "Id": 383,
                "LastUpdated": "/Date(1338347251080+0000)/",
                "Title": "Mitigating Risk - Why Sticking with Windows XP is a Bad Idea",
                "Url": "http://infra2apps.blob.core.windows.net/eventapp/Mitigating Risk - Why Sticking with Windows XP is a Bad Idea - IDC - May 2012_booth2.pdf"
            
        ],
        "Id": 2,
        "ImageUrl": "http://infra2apps.blob.core.windows.net/eventapp/Windows-brand.png",
        "Name": "Windows the right choice for business",
        "Sessions": [
            
                "Description": "Microsoft and HP are partnering together to migrate customers to Windows 7 while working closely together to build new Windows 8 products that will easily integrate into a Windows 7 environment.   This session provides insight on how these new offerings will provide enterprise grade solutions with no compromise business devices that increase productivity, security, and manageability and the path to get there.",
                "EndDate": "/Date(1338935400000+0000)/",
                "FriendlyName": "TB3256",
                "Id": 3,
                "Location": "TBD",
                "Speakers": [
                    
                        "Company": "Microsoft",
                        "Email": "snagy@microsoft.com",
                        "Name": "Sara Nagy",
                        "Title": "Senior Account Manager - OEM"
                    
                ],
                "StartDate": "/Date(1338932700000+0000)/",
                "Title": "Preparing for Windows 8"
            
        ]
    ,
    
        "Contents": [
            
                "Id": 382,
                "LastUpdated": "/Date(1338347251043+0000)/",
                "Title": "HP EDW Appliance Solution Brief",
                "Url": "http://infra2apps.blob.core.windows.net/eventapp/HP EDW Appliance Solution Brief_booth3.pdf"
            ,
            
                "Id": 380,
                "LastUpdated": "/Date(1338347250970+0000)/",
                "Title": "HP DBCA Datasheet",
                "Url": "http://infra2apps.blob.core.windows.net/eventapp/11475_DBCA-Datasheet_booth3.pdf"
            
        ],
        "Id": 3,
        "ImageUrl": "http://infra2apps.blob.core.windows.net/eventapp/SQL.png",
        "Name": "Enterprise Information Platform",
        "Sessions": [
            
                "Description": "The Database Consolidation appliance integrates software and harware into a turnkey solution that creates tremendous opportunities to virtualize demanding applications requiring enterprise-class resiliency. This session will dive into this NEW Private Cloud Appliance, leveraging virtualization and tuned and balanced infrastructure to deliver Private Cloud capabilities. We’ll go into detail including how to inventory and gather performance characteristics to provide detailed appliance-specific sizing and placement guidance using the MAP toolkit, how the appliance architecture enables high IO performance, isolation. and resiliency, and into details around core operational capabilities such as P-to-V and self-service workflow-enabled provisioning of new instances. Also, we will cover advanced capabilities such as chargeback, sustained engineering (upgrades and patching), load balancing with Live Demos that will show off the core capabilities of the appliance.",
                "EndDate": "/Date(1339017300000+0000)/",
                "FriendlyName": "TB3323",
                "Id": 5,
                "Location": "TBD",
                "Speakers": [
                    
                        "Company": "Microsoft",
                        "Email": "markmort@microsoft.com",
                        "Name": "Mark Mortimore",
                        "Title": "Senior Program Manager, SQL Server Appliances"
                    
                ],
                "StartDate": "/Date(1339014600000+0000)/",
                "Title": "Cloud on your terms - Database Consolidation Appliance"
            ,
            
                "Description": "Leveraging virtual and scalable infrastructure - 100s of servers can be efficiently, reliably, and manageably consolidated. This session will dive into the NEW DBC Appliance, leveraging virtualization and tuned and balanced infrastructure.  Using demos, we will show all phases of consolidation including how to assess environments using the MAP toolkit, details around core operational capabilities such as P-to-V and self-service workflow-enabled provisioning of new fully configured servers.  Also, we will cover advanced capabilities such as chargeback, s load balancing…  ",
                "EndDate": "/Date(1339006800000+0000)/",
                "FriendlyName": "DT3324",
                "Id": 6,
                "Location": "TBD",
                "Speakers": [
                    
                        "Company": "Microsoft",
                        "Email": "markmort@microsoft.com",
                        "Name": "Mark Mortimore",
                        "Title": "Senior Program Manager, SQL Server Appliances"
                    
                ],
                "StartDate": "/Date(1339005600000+0000)/",
                "Title": "Database Consolidation & Private Cloud Appliance"
            
        ]
    ,
    
        "Contents": [],
        "Id": 4,
        "ImageUrl": "http://infra2apps.blob.core.windows.net/eventapp/WinStorageSvr.png",
        "Name": "Windows Storage Server",
        "Sessions": []
    ,
    
        "Contents": [],
        "Id": 5,
        "ImageUrl": "http://infra2apps.blob.core.windows.net/eventapp/SQL.png",
        "Name": "Platform Modernization/Migration",
        "Sessions": [
            
                "Description": "Microsoft and HP engineering have collaborated on delivering mission critical systems which outperform historic tier 1 platforms.   Although many companies rely on the combination of HP and Microsoft for Mission Critical workloads, there has been a lingering doubt that the combined platform can scale to the needs of large enterprises currently relying on IBM Mainframes.  This session will describe a signficant study just completed that puts to rest the myths that mainframes are the only platform that scales, can support high-IO and delivery mission critical capabilities.  Finally an apples to apples comparison that you can use as you modernize your IT enviornment.",
                "EndDate": "/Date(1339093200000+0000)/",
                "FriendlyName": "DT3471",
                "Id": 8,
                "Location": "TBD",
                "Speakers": [
                    
                        "Company": "Microsoft",
                        "Email": "scorosen@microsoft.com",
                        "Name": "Scott Rosenbloom",
                        "Title": "SSP Platform Modernization"
                    
                ],
                "StartDate": "/Date(1339092000000+0000)/",
                "Title": "Mainframe Alternative: Windows Server, SQL Server and HP DL 980"
            
        ]
    
]

【问题讨论】:

@Logical — 在 cmets 中,仅支持链接的内联语法:[The title](http://example.com/) 【参考方案1】:

您的响应不是有效的 JSON。您无法使用标准 JSON 解析器对其进行解析。 (您可以使用http://jsonlint.com/ 进行验证。)

//编辑: 因此,在您进行编辑后,您确实拥有有效的 JSON 数据。要解析它,您可以使用您找到的任何 JSON 解析框架(一个流行的框架,例如 json-framework)。

但如果你只为 ios5 构建,你可以使用系统库NSJSONSerialization。

【讨论】:

【参考方案2】:

抱歉,由于时间问题没有解释下面的代码

-(void) dataRecieved: (NSDictionary *) receivedDict

 NSArray *contentsArray = [receivedDict objectForKey:@"Contents"];
 NSArray *sessionsArray = [receivedDict objectForKey:@"Sessions"];

 for (NSDictionary *contentsDict in contentsArray )
    
        Contents *objContents = [[Contents alloc]init];
        objContents.id = [contentsDict objectForKey:@"ID"];
        objContents.lastUpdate = [contentsDict objectForKey:@"LastUpdate"];
        objContents.title = [contentsDict objectForKey:@"Title"];

        [contentObjectsArray addObject: objContents]; 
    

    for (NSDictionary *sessionsDict in sessionsArray )
    
        Sessions *objSessions = [[Sessions alloc]init];
        objSessions.id = [contentsDict objectForKey:@"ID"];
        objSessions.endDate = [contentsDict objectForKey:@"EndDate"];

        NSArray *speakersArray = [receivedDict objectForKey:@"Speakers"];

        for (NSDictionary *spearkersDict in speakersArray )
        
            Speakers *objSpeakers = [[Speakers alloc]init];
            objSpeakers.title = [spearkersDict objectForKey:@"Title"];
            [objSessions.speakerssObjectsArray addObject: objSpeakers];
        

        [sessionsObjectsArray addObject:objSessions]; 
    

【讨论】:

【参考方案3】:

如果您面向 iOS 5 或更高版本,JSON 支持是原生的,因此您无需添加任何外部库或实现解析器。您只需使用 NSJSONSerialization。

See the documentation

示例代码:

NSError* error = nil;

NSArray* parsed = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

if(!error) 
    //Process here

如果您的目标 iOS 版本低于 iOS 5,则原生不支持 JSON 解析,您必须自己实现解析器,或使用适合您需要的外部库。 库示例: SBJSON

【讨论】:

【参考方案4】:

使用 SBJsonParser 解析 JSON,您可以使用此 link 可视化您的 JSON,以便您知道将在哪里使用哪个数据结构,其余的就像 @imsult 所说的那样。

【讨论】:

以上是关于如何实现 JSON 解析代码以获取对 NSArray 的响应?的主要内容,如果未能解决你的问题,请参考以下文章

将 JSON 放入数组中

Js如何实现对json克隆

数据以 JSON 对象的形式传入,如何解析?

如何在 Typescript 中保持代码 DRY 的同时解析多个 Json 文件?

请问PHP如何解析这样的json值?如何获取其中某个值内容呢? 代码如下:

如何使用目标 C 解析 JSON 并获取特定值? [复制]