1. 程式人生 > >cJSON庫(構建json與解析json字串)-c語言

cJSON庫(構建json與解析json字串)-c語言

1、c語言獲取json中的資料。

1.1、先要有cJOSN庫,兩個檔案分別是cJSON.c和cJSON.h。
1.2、感性認識

char * json = "{ \"json\" : { \"id\":1, \"nodeId\":11, \"deviceId\":111, \"deviceName\":\"aaa\", \"ieee\":\"01212\", \"ep\":\"1111\", \"type\":\"bbb\" }}";
char * json1 = "{\"id\":1, \"nodeId\":11, \"deviceId\":111, \"deviceName\":\"aaa\"}";
cJSON * root;
cJSON * format;
int value_int;
char * value_string;


root = cJSON_Parse(json); 
format = cJSON_GetObjectItem(root,"json");   
value_int = cJSON_GetObjectItem(format,"nodeId")->valueint; 
value_string = cJSON_GetObjectItem(format,"ieee")->valuestring; 
printf( "%d\n", value_int );
printf( "%s\n", value_string );
cJSON_Delete(root);
	
root = cJSON_Parse(json1); 
value_int = cJSON_GetObjectItem(root,"id")->valueint; 
value_string = cJSON_GetObjectItem(root,"deviceName")->valuestring; 
printf( "%d\n", value_int );
printf( "%s\n", value_string );
cJSON_Delete(root);
結果:
11
01212
1
aaa

2、cJSON庫

2.1、json的資料結構 

c語言中json資料是採用連結串列儲存的

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; 

3、cJSON使用

{   
    "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
    }
}

3.1、字串解析成json結構體

3.1.1、講字串解析成json結構體。 

cJSON *root = cJSON_Parse(my_json_string); 

3.1.2、獲取某個元素  

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

3.1.3、講json結構體轉換成字串 

char *rendered=cJSON_Print(root); 

3.1.4、刪除 

cJSON_Delete(root); 

3.2、構建一個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)
out =cJSON_Print(root);
printf("%s\n",out); 
cJSON_Delete(root);
free(out);