目标: 很多程序支持的参数很多,例如图像处理时,牵扯到太多的图像相关细节,可通过json文件快速描述这些参数,软件去解析json文件。
相关参考
快速使用
json格式
/* cJSON Types: */#define cJSON_False (1 << 0) // 逻辑值 true 或者 false#define cJSON_True (1 << 1)#define cJSON_NULL (1 << 2)#define cJSON_Number (1 << 3) // 数字(整数或浮点数)#define cJSON_String (1 << 4) // 字符串(双引号中)#define cJSON_Array (1 << 5) // 数组(在中括号中)#define cJSON_Object (1 << 6) // 对象(在大括号中)
例如:
{"flag":true,"rouble":null,"num0":30,"num1":3.2,"num2":-3.2,"ip":"192.168.1.7","arr0":[1,2,3],"arr1":["n1","n2","n3"],"arr2":[{"name":"Diaos","age":18},{"name":"Goddess" ,"age":16}]}
JSON书写规则
1.属性名必须是字符串,且双引号。
2.最后一个]或者}后边不能跟”,”,不是最后一个,则后边必须跟“,”
3.类型:字符串必须用双引号,可加转义字符”””来表达引号字符串
4.不能有注释,可以加入一个不去解析的字段,
cjson 使用demo
/* The cJSON structure: */typedef struct cJSON{/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */struct cJSON *next;struct cJSON *prev;/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */struct cJSON *child; // 子字段/* The type of the item, as above. */int type; // 要去解析json的类型,然后用下边的类型去查找/* The item's string, if type==cJSON_String and type == cJSON_Raw */char *valuestring;/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */int valueint;/* The item's number, if type==cJSON_Number */double valuedouble;/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */char *string; // 当前字段的句柄描述,也就是key} cJSON;
通过结构,可以看出:json用一个带子链的链表去描述整体字段,这在内核总线架构中很常见,不在描述。
尝试用json去解析上述文件:
#include "cJSON.h"int parse_config(const char * jsbuf){cJSON *root = NULL;cJSON *node = NULL;root = cJSON_Parse(jsbuf);if ( NULL == root ) {printf("%s:Parse root info json failed!", __func__);return -1;}node = cJSON_GetObjectItem((cJSON *)root, "flag");if ( (NULL != node) && (node->type & 3))printf("flag is %d", node->valueint); // 逻辑值node = cJSON_GetObjectItem((cJSON *)root, "ip");if ( NULL != node && (node->type == cJSON_String ))printf("ip is %s", node->valuestring); // 字符串char*// 数组cJSON * node_arr = cJSON_GetObjectItem((cJSON *)root, "arr0");cJSON* loop;int index = 0;cJSON_ArrayForEach(loop, node_arr){printf("test_arr1[%d] is %d\n",index,loop->valueint);index ++;}cJSON * node_arr = cJSON_GetObjectItem((cJSON *)root, "arr2");cJSON_ArrayForEach(loop, node_arr){printf("test_arr2[%d]-name is %s\n",index,cJSON_GetObjectItem((cJSON *)loop, "name"));printf("test_arr2[%d]-age is %d\n",index,cJSON_GetObjectItem((cJSON *)loop, "age"));index ++;}// free一定要放到所有程序最后去释放,否则其中字符串会丢失cJSON_free(root);}
