cJONS序列化工具解读三(使用案例)

 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;
}

 

posted @ 2016-05-19 09:24  狼行博客园  阅读(601)  评论(0编辑  收藏  举报