cJSONコード読解(2)——cJSON紹介

3046 ワード

cJSONは軽量で、持ち運びが便利で、単一ファイルで、簡単で、ANSI-C標準に合致するJSON解析器です.
次に、使用する2つの例を見てみましょう(この2つの例もネット上から来ています).
解析jsonデータ:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
#include "cJSON.h"

void parse_json_data()
{
    char text[] = "{\"name\":\"jack\",\"age\":18}";

    cJSON *json , *json_value , *json_timestamp;
    //      
    json = cJSON_Parse(text);
    if (!json)
    {
        printf("Error before: [%s]
",cJSON_GetErrorPtr()); } else { // json_value = cJSON_GetObjectItem( json , "age"); if( json_value->type == cJSON_Number ) { // valueint printf("age:%d\r
",json_value->valueint); } // json_timestamp = cJSON_GetObjectItem( json , "name"); if( json_timestamp->type == cJSON_String ) { // valuestring printf("%s\r
",json_timestamp->valuestring); } // cJSON_Delete(json); } }
 
  
 

生成json数据:

void create_json_data()
{
   
    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);
    cJSON_Delete(pRoot);
    //free(szJSON);

    pRoot = cJSON_Parse(szJSON);
    pArray = cJSON_GetObjectItem(pRoot, "students_info");
    if (NULL == pArray)
    {
        return ;
    }

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