今天是端午节,特意写了篇博客,之前工作中遇到用CJson来存储配置文件,对于有的人来说,没用过这种数据格式,更不知道如何使用它,现在我就用我对CJson的理解来记录下CJson的基础使用。
cJSON简介:
JSON(JavaScriptObject Notation)是一种轻量级的数据交换格式。它基于JavaScript的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。 cJSON是一个超轻巧,携带方便,单文件,简单的可以作为ANSI-C标准的JSON解析器。了解json请参考其官网http://json.org/,cJSON 下载地址:http://sourceforge.net/projects/cjson/?source=typ_redirect , 文件只有几十k,下载完成后解压,cJOSN库,仅有两个文件cJSON.c和cJSON.h。 test.c 是下载后自带的一个小小的例子,通过这个例子的学习,很快就能掌握json数据结构的构造和解析。 自带例子编译方式如下: gcc cJSON.c test.c -o jsontest -lm 此处记住一定要包含 -lm,因为cJSON.c里面用到了两个数学函数pow floor,否则编译会报错。 一、json库的简单介绍和简单实际应用 cJSON结构体:
typedef struct cJSON
{
struct cJSON *next,*prev;// 数组 对象数据中用到 struct cJSON *child;// 数组 和对象中指向子数组对象或值 int type;// 元素的类型,如是对象还是数组 char *valuestring;// 如果是字符串 int valueint; // 如果是数值 double valuedouble;// 如果类型是cJSON_Number char *string;// The item's name string, if this item is the child of, or is in the list of subitems of an object. } cJSON;
1、cJSON存储的时候是采用链表存储的,其访问方式很像一颗树。每一个节点可以有兄妹节点,通过next/prev指针来查找,它类似双向链表;每个节点也可以有孩子节点,通过child指针来访问,进入下一层。不过,只有节点是对象或数组才可以有孩子节点。
2、type一共有7种取值,分别是: #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
若是Number类型,则valueint或valuedouble中存储着值,若你期望的是int,则访问valueint,若期望的是 double,则访问valuedouble,可以得到值。
若是String类型的,则valuestring中存储着值,可以访问valuestring得到值。
3、string中存放的是这个节点的名字 4、用法: (1)只需在函数中includecJSON.h头文件,然后和cJSON.c或库文件libcJSON.a一起编译即可使用。
(2)具体函数用法详见cJSON.h中注释
二、使用实例
{ "name": "Jack (\"Bee\") Nimble", "format": { "type": "rect", "width": 1920, "height": 1080, "interlace": false, "frame rate": 24 } }
字符串解析成json结构体:
cJSON *
root
=
cJSON_Parse
(my_json_string);
获取某个元素:
cJSON * format = cJSON_GetObjectItem (root,"format"); int framerate = cJSON_GetObjectItem (format,"frame rate")- > valueint;
json结构体转换成字符串:
char * rendered = cJSON_Print (root);
删除:
构建一个json结构体:
cJSON *root,*fmt; char *out; root = cJSON_CreateObject (); cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble")); cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject ()); cJSON_AddStringToObject(fmt,"type", "rect"); cJSON_AddNumberToObject(fmt,"width", 1920); cJSON_AddNumberToObject(fmt,"height", 1080); cJSON_AddFalseToObject (fmt,"interlace"); cJSON_AddNumberToObject(fmt,"frame rate", 24) out = cJSON_Print (root); printf("%s\n",out); cJSON_Delete(root); free(out);
读取cjson测试:
/*********************************************************************************** { "message": "json test", "allRowCount": 2, "root": [{ "value": "2015-11-16 11:15", "id": "2015_20110.10000", "sex": "famale" }], "success": "true" } ************************************************************************************/ #include < stdio.h > #include < stdlib.h > #include "cJSON.h" static int print_jsom(char *json_string) { char *out; cJSON *jsonroot = cJSON_Parse (json_string); out = cJSON_Print (jsonroot); printf("%s\n",out); cJSON_Delete(jsonroot); free(out); return 1; } static int print_file(char *filename) { FILE *fp; int flen; char *p; if ((fp = fopen (filename, "r")) == NULL) { printf("file open error\n"); exit(0); } fseek(fp, 0, SEEK_END); flen = ftell (fp); p = (char *)malloc(flen + 1); fseek (fp, 0, SEEK_SET); fread (p , flen, 1, fp); print_jsom(p); fclose(fp); free(p); return 1; } int main (int argc, const char * argv[]) { char *filename = "ch.txt" ; print_file(filename); char *my_json_string = "{ \ \n\"message\":\"json test\", \ \n\"allRowCount\":2, \ \n\"root\":[{ \ \n \"value\":\"2015-11-16 11:15\", \ \n \"id\":\"2015_20110.10000\", \ \n \"sex\":\"famale\" \ \n }], \ \n\"success\":\"true\" \ \n}"; print_jsom(my_json_string); cJSON *jsonroot = cJSON_Parse (my_json_string); printf("success =%s\n",cJSON_GetObjectItem(jsonroot, "message")- > valuestring); int taskNum = cJSON_GetObjectItem (jsonroot,"allRowCount")- > valueint; printf("allRowCount =%d\n", taskNum); cJSON *taskArry = cJSON_GetObjectItem (jsonroot,"root");//取数组 int arrySize = cJSON_GetArraySize (taskArry);//数组大小 printf("array size:%d\n",arrySize); cJSON *tasklist = taskArry - > child;//子对象 char *value = NULL ; printf("------------------------\n"); while(tasklist!=NULL) { value = cJSON_GetObjectItem (tasklist,"value")- > valuestring; if (value && strcmp(value, "")) { printf("value =%s\n", value); } value = cJSON_GetObjectItem (tasklist,"id")- > valuestring; if (value && strcmp(value, "")) { printf("id =%s\n", value); } value = cJSON_GetObjectItem (tasklist,"sex")- > valuestring; if (value && strcmp(value, "")) { printf("sex =%s\n", value); } tasklist = tasklist - > next; } cJSON_Delete(jsonroot); return 1; }
编译运行:
gcc -o main cJSON.c main.c -lm ./main
创建cjson并显示:
#include < stdio.h > #include < stdlib.h > #include "cJSON.h" int main (int argc, const char * argv[]) { 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); printf("%s\n",szJSON); cJSON_Delete(pRoot); pRoot = cJSON_Parse (szJSON); pArray = cJSON_GetObjectItem (pRoot, "students_info"); if (NULL == pArray) { return -1; } int iCount = cJSON_GetArraySize (pArray); int i = 0 ; for (; i < iCount ; ++i) { cJSON* pItem = cJSON_GetArrayItem (pArray, i); if (NULL == pItem){ continue; } char *strName = cJSON_GetObjectItem (pItem, "name")- > valuestring; char *trSex = cJSON_GetObjectItem (pItem, "sex")- > valuestring; int iAge = cJSON_GetObjectItem (pItem, "age")- > valueint; printf("---name =%s\n", strName); printf("---sex =%s\n", trSex); printf("---age =%d\n", iAge); } cJSON_Delete(pRoot); free(szJSON); return 0; }
编译运行:
gcc -o create cJSON.c create.c -lm ./create