cjson源码学习
cjson源代码下载地址 https://sourceforge.net/projects/cjson/?source=directory 主要是cJSON.h,cJSON.c,test.c三个文件 json结构json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。 JSON 值:
json的详细语法,规则可自行搜索 josn.cn学习地址: http://json.cn/ /* 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
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively,use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item,as above. */
char *valuestring; /* The item's string,if type==cJSON_String */
int valueint; /* The item's number,if type==cJSON_Number */
double valuedouble; /* The item's number,if type==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;
整个结构体表示一个cjson结构,结构体存放的相关内容: http://json.cn/ { 直接debug源码中的test.c,一步步的运行下去,查看该过程和其中的结构体第一个要转换的字符串如下: char text1[] = "{n"name": "Jack ("Bee") Nimble",n"format": {"type": "rect",n"width": 1920,n"height": 1080,n"interlace": false,"frame rate": 24n}n}";
主要是将字符串转换成cJSON结构体对象,这里有装换成字符串,数组,对象等等方法 /* Parser core - when encountering text,process appropriately. */
static const char *parse_value(cJSON *item,const char *value)
{
if (!value) return 0; /* Fail on null. */
if (!strncmp(value,"null",4)) { item->type = cJSON_NULL; return value + 4; }
if (!strncmp(value,"false",5)) { item->type = cJSON_False; return value + 5; }
if (!strncmp(value,"true",4)) { item->type = cJSON_True; item->valueint = 1; return value + 4; }
if (*value == '"') { return parse_string(item,value); }
if (*value == '-' || (*value >= '0' && *value <= '9')) { return parse_number(item,value); }
if (*value == '[') { return parse_array(item,value); }
if (*value == '{') { return parse_object(item,value); }
ep = value; return 0; /* failure. */
}
下面是debug过程中的截图,其中有需要经常处理里面的空格等无效字符函数skip(),然后是具体对象里面的各个转换函数的调用(parse_xx()) parse_sting函数只要是处理了各种编码的字符串,分配了内存,赋值给cjson* item对象 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |