cJSON是一个轻巧,携带方便,单文件,简单的并且符合ANSI-C标准的JSON解析器。
下面看看使用它的两个例子(这两个例子也是来源于网上)。
解析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]\n",cJSON_GetErrorPtr());
}
else
{
// 解析值
json_value = cJSON_GetObjectItem( json , "age");
if( json_value->type == cJSON_Number )
{
// 从valueint中获得结果
printf("age:%d\r\n",json_value->valueint);
}
// 解析时间戳
json_timestamp = cJSON_GetObjectItem( json , "name");
if( json_timestamp->type == cJSON_String )
{
// valuestring中获得结果
printf("%s\r\n",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);
}