cJSON各函数实现的功能

来源:互联网 发布:sql server 恢复挂起 编辑:程序博客网 时间:2024/06/06 03:54

参考资料:

http://blog.csdn.net/daisy09/article/details/7086746

cJSON简介:

JSON(JavaScriptObject Notation)是一种轻量级的数据交换格式。它基于JavaScript的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

cJSON是一个超轻巧,携带方便,单文件,简单的可以作为ANSI-C标准的JSON解析器。

cJSON结构体:

typedefstruct cJSON {

structcJSON *next,*prev;

struct cJSON *child;

int type;

char * valuestring;

int valueint;

double valuedouble;

char *string;

}cJSON;

1cJSON存储的时候是采用链表存储的,其访问方式很像一颗树。每一个节点可以有兄妹节点,通过next/prev指针来查找,它类似双向链表;每个节点也可以有孩子节点,通过child指针来访问,进入下一层。

不过,只有节点是对象或数组才可以有孩子节点。

2type一共有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类型,则valueintvaluedouble中存储着值,若你期望的是int,则访问valueint,若期望的是double,则访问valuedouble,可以得到值。

若是String类型的,则valuestring中存储着值,可以访问valuestring得到值。

3string中存放的是这个节点的名字

 

二、用法举例

比如你有一个json数据 
Javascript代码  
{   
    "name": "Jack (\"Bee\") Nimble",    
    "format": {   
        "type":       "rect",    
        "width":      1920,    
        "height":     1080,    
        "interlace":  false,    
        "frame rate": 24   
    }   

{
    "name": "Jack (\"Bee\") Nimble", 
    "format": {
        "type":       "rect", 
        "width":      1920, 
        "height":     1080, 
        "interlace":  false, 
        "frame rate": 24
    }
}

那么你可以 

1.cJSON_Parse:将json数据解析成json结构体

cJSON *root = cJSON_Parse(my_json_string);

2.cJSON_GetObjectItem:获取某个元素

cJSON *format = cJSON_GetObjectItem(root,"format");   

int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint; 

3.cJSON_Print:将就SON结构体转化成字符串

char *rendered=cJSON_Print(root);

4.cJSON_Delete:删除一个json结构体

cJSON_Delete(root); 

5:构建一个json结构体 
cJSON *root,*fmt;   
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);