cJSON使用案例
由了解了cJSON的數據結構,接口以及實現之後,那麼我們來舉例說明其使用。
本例子是一個簡單的學生信息表格管理,我們通過鍵值對的方式向json中增加元素信息。
然後可以格式化輸出結果,也能夠反向的由字符串輸出生成原cJSON對象。
int Test_cJSON()
{
cJSON* pRoot = cJSON_CreateObject();
cJSON* pArray = cJSON_CreateArray();
cJSON_AddItemToObject(pRoot, "students_info", pArray);
char* szOut = cJSON_Print(pRoot);
cJSON* pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem, "name", "chenzhongjing");
cJSON_AddStringToObject(pItem, "sex", "male");
cJSON_AddNumberToObject(pItem, "age", 28);
cJSON_AddItemToArray(pArray, pItem);
pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem, "name", "fengxuan");
cJSON_AddStringToObject(pItem, "sex", "male");
cJSON_AddNumberToObject(pItem, "age", 24);
cJSON_AddItemToArray(pArray, pItem);
pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem, "name", "tuhui");
cJSON_AddStringToObject(pItem, "sex", "male");
cJSON_AddNumberToObject(pItem, "age", 22);
cJSON_AddItemToArray(pArray, pItem);
char* szJSON = cJSON_Print(pRoot);
cout << szJSON << endl;
cJSON_Delete(pRoot);
//free(szJSON);
pRoot = cJSON_Parse(szJSON);
pArray = cJSON_GetObjectItem(pRoot, "students_info");
if (NULL == pArray)
{
return -1;
}
int iCount = cJSON_GetArraySize(pArray);
for (int i = 0; i < iCount; ++i)
{
cJSON* pItem = cJSON_GetArrayItem(pArray, i);
if (NULL == pItem)
{
continue;
}
string strName = cJSON_GetObjectItem(pItem, "name")->valuestring;
string strSex = cJSON_GetObjectItem(pItem, "sex")->valuestring;
int iAge = cJSON_GetObjectItem(pItem, "age")->valueint;
}
cJSON_Delete(pRoot);
free(szJSON);
}

亦或是對於格式化的字符串,交給cJSON管理,自動識別,產生類型輸出。
/* Parse text to JSON, then render back to text, and print! */
void doit(char *text)
{
char *out; cJSON *json;
json = cJSON_Parse(text);
if (!json) { printf("Error before: [%s]\n", cJSON_GetErrorPtr()); }
else
{
out = cJSON_Print(json);
cJSON_Delete(json);
printf("%s\n", out);
free(out);
}
}
/* Read a file, parse, render back, etc. */
void dofile(char *filename)
{
FILE *f; long len; char *data;
f = fopen(filename, "rb");
assert(f);
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, 0, SEEK_SET);
data = (char*)malloc(len + 1);
memset(data, 0, sizeof(char)*(len + 1));
fread(data, 1, len, f);
printf("%s", data);
fclose(f);
doit(data);
free(data);
}
int main()
{
char text1[] = "{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\": \"rect\", \n\"width\": 1920, \n\"height\": 1080, \n\"interlace\": false,\"frame rate\": 24\n}\n}";
doit(text1);
return 0;
}
