cJSON 使用详解

在学了在学了! 2020-08-20 11:09:57 3356

由于c语言中,没有直接的字典,字符串数组等数据结构,所以要借助结构体定义,处理json。如果有对应的数据结构就方便一些, 如python中用json.loads(json)就把json字符串转变为内建的数据结构处理起来比较方便。

一个重要概念:

在cjson中,json对象可以是json,可以是字符串,可以是数字。。。

cjson数据结构定义:

 #define cJSON_False 0

 #define cJSON_True 1

 #define cJSON_NULL 2

 #define cJSON_Number 3

#define cJSON_String 4

 #define cJSON_Array 5

#define cJSON_Object 6

 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. cjson结构的类型上面宏定义的7中之一*/

    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;

#define cJSON_False 0

 #define cJSON_True 1

 #define cJSON_NULL 2

 #define cJSON_Number 3

 #define cJSON_String 4

#define cJSON_Array 5

 #define cJSON_Object 6

 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. cjson结构的类型上面宏定义的7中之一*/

    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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
<

一、解析json 用到的函数,在cJSON.h中都能找到:

 /* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */

extern cJSON *cJSON_Parse(const char *value);//从 给定的json字符串中得到cjson对象

/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */

extern char  *cJSON_Print(cJSON *item);//从cjson对象中获取有格式的json对象

 /* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */

extern char  *cJSON_PrintUnformatted(cJSON *item);//从cjson对象中获取无格式的json对象

/* Delete a cJSON entity and all subentities. */

extern void   cJSON_Delete(cJSON *c);//删除cjson对象,释放链表占用的内存空间

/* Returns the number of items in an array (or object). */

extern int    cJSON_GetArraySize(cJSON *array);//获取cjson对象数组成员的个数

/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */

extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//根据下标获取cjosn对象数组中的对象

 /* Get item "string" from object. Case insensitive. */

 extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//根据键获取对应的值(cjson对象)

/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */

 extern const char *cJSON_GetErrorPtr(void);//获取错误字符串

要解析的json

 {

    "semantic": {

        "slots":    {

            "name": "张三"

        }

    },

    "rc":   0,

    "operation":    "CALL",

    "service":  "telephone",

    "text": "打电话给张三"

 }

#include <stdio.h>

#include <stdlib.h>

#include "cJSON.h"

 void printJson(cJSON * root)//以递归的方式打印json的最内层键值对

 {

    for(int i=0; i<cJSON_GetArraySize(root); i++)   //遍历最外层json键值对

    {

        cJSON * item = cJSON_GetArrayItem(root, i);        

        if(cJSON_Object == item->type)      //如果对应键的值仍为cJSON_Object就递归调用printJson

            printJson(item);

        else                                //值不为json对象就直接打印出键和值

        {

            printf("%s->", item->string);

            printf("%s\n", cJSON_Print(item));

        }

    }

 }

int main()

{

    char * jsonStr = "{\"semantic\":{\"slots\":{\"name\":\"张三\"}}, \"rc\":0, \"operation\":\"CALL\", \"service\":\"telephone\", \"text\":\"打电话给张三\"}";

    cJSON * root = NULL;

    cJSON * item = NULL;//cjson对象

    root = cJSON_Parse(jsonStr);     

    if (!root) 

    {

        printf("Error before: [%s]\n",cJSON_GetErrorPtr());

    }

    else

    {

        printf("%s\n", "有格式的方式打印Json:");           

        printf("%s\n\n", cJSON_Print(root));

        printf("%s\n", "无格式方式打印json:");

        printf("%s\n\n", cJSON_PrintUnformatted(root));

        printf("%s\n", "一步一步的获取name 键值对:");

        printf("%s\n", "获取semantic下的cjson对象:");

        item = cJSON_GetObjectItem(root, "semantic");//

        printf("%s\n", cJSON_Print(item));

        printf("%s\n", "获取slots下的cjson对象");

        item = cJSON_GetObjectItem(item, "slots");

        printf("%s\n", cJSON_Print(item));

        printf("%s\n", "获取name下的cjson对象");

        item = cJSON_GetObjectItem(item, "name");

        printf("%s\n", cJSON_Print(item));

        printf("%s:", item->string);   //看一下cjson对象的结构体中这两个成员的意思

        printf("%s\n", item->valuestring);

        printf("\n%s\n", "打印json所有最内层键值对:");

        printJson(root);

    }

    return 0;    

}

  二、构造json:

    构造 json比较简单,添加json对象即可。参照例子一看大概就明白了。

    主要就是用,cJSON_AddItemToObject函数添加json节点。

      xtern cJSON *cJSON_CreateObject(void);

        extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);

        extern cJSON *cJSON_CreateNull(void);

        extern cJSON *cJSON_CreateTrue(void);

        extern cJSON *cJSON_CreateFalse(void);

        extern cJSON *cJSON_CreateBool(int b);

        extern cJSON *cJSON_CreateNumber(double num);

        extern cJSON *cJSON_CreateString(const char *string);

        extern cJSON *cJSON_CreateArray(void);

        extern cJSON *cJSON_CreateObject(void);

 例子:     要构建的json:

        "semantic": {

        "slots":    {

            "name": "张三"

        }

            },

            "rc":   0,

            "operation":    "CALL",

            "service":  "telephone",

            "text": "打电话给张三"

        }

        #include <stdio.h>

        #include "cJSON.h"

        int main()

        {

    cJSON * root =  cJSON_CreateObject();

     cJSON * item =  cJSON_CreateObject();

    cJSON * next =  cJSON_CreateObject();

     cJSON_AddItemToObject(root, "rc", cJSON_CreateNumber(0));//根节点下添加

     cJSON_AddItemToObject(root, "operation", cJSON_CreateString("CALL"));

    cJSON_AddItemToObject(root, "service", cJSON_CreateString("telephone"));

     cJSON_AddItemToObject(root, "text", cJSON_CreateString("打电话给张三"));

     cJSON_AddItemToObject(root, "semantic", item);//root节点下添加semantic节点

    cJSON_AddItemToObject(item, "slots", next);//semantic节点下添加item节点

    cJSON_AddItemToObject(next, "name", cJSON_CreateString("张三"));//添加name节点

    printf("%s\n", cJSON_Print(root));

    return 0;

}

原文连接:https://blog.csdn.net/qq_32172673/article/details/88305781
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
<
声明:本文内容由易百纳平台入驻作者撰写,文章观点仅代表作者本人,不代表易百纳立场。如有内容侵权或者其他问题,请联系本站进行删除。
红包 点赞 收藏 评论 打赏
评论
0个
内容存在敏感词
手气红包
    易百纳技术社区暂无数据
相关专栏
置顶时间设置
结束时间
删除原因
  • 广告/SPAM
  • 恶意灌水
  • 违规内容
  • 文不对题
  • 重复发帖
打赏作者
易百纳技术社区
在学了在学了!
您的支持将鼓励我继续创作!
打赏金额:
¥1易百纳技术社区
¥5易百纳技术社区
¥10易百纳技术社区
¥50易百纳技术社区
¥100易百纳技术社区
支付方式:
微信支付
支付宝支付
易百纳技术社区微信支付
易百纳技术社区
打赏成功!

感谢您的打赏,如若您也想被打赏,可前往 发表专栏 哦~

举报反馈

举报类型

  • 内容涉黄/赌/毒
  • 内容侵权/抄袭
  • 政治相关
  • 涉嫌广告
  • 侮辱谩骂
  • 其他

详细说明

审核成功

发布时间设置
发布时间:
是否关联周任务-专栏模块

审核失败

失败原因
备注
拼手气红包 红包规则
祝福语
恭喜发财,大吉大利!
红包金额
红包最小金额不能低于5元
红包数量
红包数量范围10~50个
余额支付
当前余额:
可前往问答、专栏板块获取收益 去获取
取 消 确 定

小包子的红包

恭喜发财,大吉大利

已领取20/40,共1.6元 红包规则

    易百纳技术社区