VC++6.0 MFC 下面最合適最簡單的JSON類

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;

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中存放的是這個節點的名字



二、用法舉例

比如你有一個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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章