由于C语言本身不支持JSON数据,所以我们可以通过cJSON使得C语言支持JSON格式的数据。
使用说明:下载以上链接的文件,里面有c和h文件,在C代码中包含头文件
#include <cJSON.h>
在编译时,和cJSON.c一起编译,比如这样:
gcc test.c cJSON.c -o out
下面是代码示例:
构造一个形如
{ "username": "changzhi","password":"12345",}的JSON字符串
char *CreateAuthJSONData(char username[],char password[],char hostname[],char address[]) { cJSON *root; //声明一个cJSON数据 char *data = NULL; //create a json root = cJSON_CreateObject(); //add value into "root" cJSON_AddStringToObject(root,"username",username); cJSON_AddStringToObject(root,"password",password); cJSON_AddStringToObject(root,"hostname",hostname); cJSON_AddStringToObject(root,"address",address); data = cJSON_Print(root);//将JSON转换成char数组并返回 return data; }
recvJSON = cJSON_Parse(szBuffer); //parse str to json size = cJSON_GetArraySize(recvJSON);//get json size for (i = 0; i < size; i++){ arrayItem = cJSON_GetArrayItem(recvJSON,i); pr = cJSON_Print(arrayItem); printf("%s -> %s\n",arrayItem->string,pr); }
其中值得注意的是,在结构体cJSON中:
/* 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;
char *string 对应的就是json中的key部分。