JSON是一種輕量級(jí)的數(shù)據(jù)交換格式,常用于Web應(yīng)用程序中傳輸數(shù)據(jù)。在iOS中,我們經(jīng)常需要將從服務(wù)器返回的JSON數(shù)據(jù)轉(zhuǎn)化為Model對(duì)象。C語言提供了一種方便的方式來進(jìn)行JSON解析。
首先,我們需要導(dǎo)入C語言的JSON解析庫,例如 cJSON。在 Xcode 項(xiàng)目中選擇 File >Add Files to "project name",然后選中 cJSON.c 和 cJSON.h 文件。然后在需要使用解析的文件中引入頭文件:
#include "cJSON.h"
假設(shè)從服務(wù)器獲取的JSON數(shù)據(jù)如下所示:
{ "name": "Jack", "age": 28, "isMarried": true, "address": { "country": "China", "city": "Beijing" }, "skills": [ "C", "Objective-C", "Swift" ] }
我們可以定義一個(gè)對(duì)應(yīng)的Model類:
typedef struct { char *name; int age; bool isMarried; struct { char *country; char *city; } address; char **skills; int skillsCount; } Person;
接著,我們就可以編寫解析的代碼:
cJSON *json = cJSON_Parse(jsonString); Person person; person.name = cJSON_GetObjectItem(json, "name")->valuestring; person.age = cJSON_GetObjectItem(json, "age")->valueint; person.isMarried = cJSON_GetObjectItem(json, "isMarried")->valueint; person.address.country = cJSON_GetObjectItem(cJSON_GetObjectItem(json, "address"), "country")->valuestring; person.address.city = cJSON_GetObjectItem(cJSON_GetObjectItem(json, "address"), "city")->valuestring; cJSON *skillsArray = cJSON_GetObjectItem(json, "skills"); person.skillsCount = cJSON_GetArraySize(skillsArray); person.skills = malloc(person.skillsCount * sizeof(char *)); for (int i = 0; i< person.skillsCount; i++) { cJSON *skillItem = cJSON_GetArrayItem(skillsArray, i); person.skills[i] = skillItem->valuestring; } cJSON_Delete(json);
最后,不要忘記在使用完畢后釋放申請(qǐng)的內(nèi)存:
for (int i = 0; i< person.skillsCount; i++) { free(person.skills[i]); } free(person.skills);
至此,我們就可以將JSON數(shù)據(jù)解析成對(duì)應(yīng)的Model對(duì)象。