Explanation of cJONS serialization tool 3 (use cases) and cjons serialization
CJSON use case
After understanding the data structure, interfaces, and implementation of cJSON, we will give an example to illustrate how to use it.
This example is a simple student information table management. We add element information to json using key-value pairs.
The output result can be formatted, or the original cJSON object can be generated by the string output in reverse direction.
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);}
You can also send formatted strings to cJSON for management, automatic identification, and type output.
/* 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;
}