歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用C語言玩JSON

用C語言玩JSON

日期:2017/3/1 9:44:23   编辑:Linux編程

JSON是網絡上常見的數據傳輸格式之一,尤其AJAX常用。最近想用C++解析JSON,查了一下JSON的官方網站,翻出來一個不錯的庫——cJSON庫。貌似使用的人不是很多,但是只有兩個文件,代碼量不大,基本實現了常見的所有功能,用起來還是挺方便的。

--------------------------------------分割線 --------------------------------------

Struts中異步傳送XML和JSON類型的數據 http://www.linuxidc.com/Linux/2013-08/88247.htm

Linux下JSON庫的編譯及代碼測試 http://www.linuxidc.com/Linux/2013-03/81607.htm

jQuery 獲取JSON數據[$.getJSON方法] http://www.linuxidc.com/Linux/2013-03/81673.htm

用jQuery以及JSON包將表單數據轉為JSON字符串 http://www.linuxidc.com/Linux/2013-01/77560.htm

在C語言中解析JSON配置文件 http://www.linuxidc.com/Linux/2014-05/101822.htm

--------------------------------------分割線 --------------------------------------

cJSON的網址:http://sourceforge.net/projects/cjson/

打開cJSON.h文件看看數據類型和函數名基本上就能上手了。

主要數據類型:

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結構體,使用了鏈表存儲方式。type代表這個結構體的類型,包括數、字符串、數組、json對象等。如果代表的是實數,則valuedouble就存儲了這個實數取值,其余成員類似容易看懂。

幾個常用函數

extern cJSON *cJSON_Parse(const char *value);//解析一個json字符串為cJSON對象
extern char  *cJSON_Print(cJSON *item);//將json對象轉換成容易讓人看清結構的字符串
extern char  *cJSON_PrintUnformatted(cJSON *item);//將json對象轉換成一個很短的字符串,無回車
extern void   cJSON_Delete(cJSON *c);//刪除json對象
extern int	  cJSON_GetArraySize(cJSON *array);//返回json數組大小
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//返回json數組中指定位置對象
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//返回指定字符串對應的json對象
extern cJSON *cJSON_CreateIntArray(int *numbers,int count);//生成整型數組json對象
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);//向數組中添加元素

README文件中也提供了一些簡單的說明和例子程序。cJSON是個簡單而好用的C語言JSON庫,需要用C/C++處理JSON的話強烈推薦~

Copyright © Linux教程網 All Rights Reserved