微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

由于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 -> %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部分。

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

原文地址:https://www.jb51.cc/json/289953.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐