JSON是一种轻量级的数据交换格式,基于JavaScript的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯。这些特性使JSON成为理想的数据交换语言。易于人阅读与编写,同时也易于机器解析和生成。
cJSON是一个超轻巧,携带方便,单文件,简单的可以作为ANSI-C标准的JSON解析器。
cJSON下载地址:点击打开链接
查看cJSON代码可以看到,cJSON结构体如下:
typedef struct cJSON {
struct cJSON *next,*prev;
struct cJSON *child;
int type;
char *valuestring;
int valueint;
double valuedouble;
char *string;
} cJSON;
共有7种类型:
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
#include
#include
#include"cJSON.h"
int main(int argc,const char *argv[])
{
cJSON *root,*fmt,*json,*format;
char *out;
int i;
//创建JSON字符串
root = cJSON_CreateObject();
cJSON_AddItemToObject(root,"name",cJSON_CreateString("Jack"));
cJSON_AddItemToObject(root,"format",fmt = cJSON_CreateObject());
cJSON_AddStringToObject(fmt,"type","rect");
cJSON_AddNumberToObject(fmt,"width",1000);
cJSON_AddNumberToObject(fmt,"height",2000.123);
// cJSON_AddFalseToObject(fmt,"interlace");
cJSON_AddNumberToObject(fmt,"frame rate",24);
out = cJSON_Print(root); //out中保存的是JSON格式的字符串
cJSON_Delete(root); //删除cJSON
printf("%s\n",out); //终端打印输出
json = cJSON_Parse(out); //解析JSON格式的字符串
free(out); //释放字符串空间
if(!json)
{
printf("Error before:[%s]\n",cJSON_GetErrorPtr());
}
else
{
//提取出各个数据并打印输出
char *name = cJSON_GetObjectItem(json,"name")->valuestring;
printf("name: %s\n",name);
format = cJSON_GetObjectItem(json,"format");
char *type = cJSON_GetObjectItem(format,"type")->valuestring;
printf("type: %s\n",type);
int width = cJSON_GetObjectItem(format,"width")->valueint;
printf("width: %d\n",width);
double height = cJSON_GetObjectItem(format,"height")->valuedouble;
printf("width: %f\n",height);
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
printf("framerate: %d\n",framerate);
}
}
运行结果: