加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过使用cJSON使得C语言支持JSON数据

发布时间:2020-12-16 19:11:36 所属栏目:百科 来源:网络整理
导读:由于C语言本身不支持JSON数据,所以我们可以通过cJSON使得C语言支持JSON格式的数据。 给出链接就是这里 使用说明:下载以上链接的文件,里面有c和h文件,在C代码中包含头文件 #include cJSON.h 在编译时,和cJSON.c一起编译,比如这样: gcc test.c cJSON.c

由于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;
 }


解析JSON字符串:

    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 -> %sn",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部分。

( 更多cJSON的内置函数请参看cJSON.h中的函数说明 )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读