Json   发布时间:2022-04-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了通过使用cJSON使得C语言支持JSON数据大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

由于C语言本身不支持JSON数据,所以我们可以通过cJSON使得C语言支持JSON格式的数据。

给出链接就是这里

@H_674_9@

使用说明:下载以上链接文件,里面有c和h文件,在C代码中包含头文件

#include <cJSON.h>
@H_674_9@ 在编译时,和cJSON.c一起编译,比如这样:

gcc test.c cJSON.c -o out
@H_674_9@ 下面是代码例:

构造一个形如

{
    "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;
 }

@H_674_9@

解析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);
    }
@H_674_9@ 其中值得注意的是,在结构体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;
@H_674_9@ @H_674_9@ char *String 对应的就是json中的key部分。

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

大佬总结

以上是大佬教程为你收集整理的通过使用cJSON使得C语言支持JSON数据全部内容,希望文章能够帮你解决通过使用cJSON使得C语言支持JSON数据所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。