cJSON使用

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

 

    一个重要概念:

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

    cjson数据结构定义:


   
   
  1. #define cJSON_False 0
  2. #define cJSON_True 1
  3. #define cJSON_NULL 2
  4. #define cJSON_Number 3
  5. #define cJSON_String 4
  6. #define cJSON_Array 5
  7. #define cJSON_Object 6
  8. typedef struct cJSON {
  9.     struct cJSON *next,*prev;     /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
  10.     struct cJSON *child;         /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
  11.     int type;                     /* The type of the item, as above. cjson结构的类型上面宏定义的7中之一*/
  12.     char *valuestring;             /* The item's string, if type==cJSON_String */
  13.     int valueint;                 /* The item's number, if type==cJSON_Number */
  14.     double valuedouble;             /* The item's number, if type==cJSON_Number */
  15.     char * string;                 /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
  16. } cJSON;

   
   
  1. #define cJSON_False 0
  2. #define cJSON_True 1
  3. #define cJSON_NULL 2
  4. #define cJSON_Number 3
  5. #define cJSON_String 4
  6. #define cJSON_Array 5
  7. #define cJSON_Object 6
  8. typedef struct cJSON {
  9.     struct cJSON *next,*prev;     /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
  10.     struct cJSON *child;         /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
  11.     int type;                     /* The type of the item, as above. cjson结构的类型上面宏定义的7中之一*/
  12.     char *valuestring;             /* The item's string, if type==cJSON_String */
  13.     int valueint;                 /* The item's number, if type==cJSON_Number */
  14.     double valuedouble;             /* The item's number, if type==cJSON_Number */
  15.     char * string;                 /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
  16. } cJSON;

 

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


   
   
  1. /* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
  2. extern cJSON *cJSON_Parse(const char *value); //从 给定的json字符串中得到cjson对象
  3. /* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
  4. extern char  *cJSON_Print(cJSON *item); //从cjson对象中获取有格式的json对象
  5. /* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
  6. extern char  *cJSON_PrintUnformatted(cJSON *item); //从cjson对象中获取无格式的json对象
  7. /* Delete a cJSON entity and all subentities. */
  8. extern void   cJSON_Delete(cJSON *c); //删除cjson对象,释放链表占用的内存空间
  9. /* Returns the number of items in an array (or object). */
  10. extern int    cJSON_GetArraySize(cJSON *array); //获取cjson对象数组成员的个数
  11. /* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
  12. extern cJSON *cJSON_GetArrayItem(cJSON *array,int item); //根据下标获取cjosn对象数组中的对象
  13. /* Get item "string" from object. Case insensitive. */
  14. extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string); //根据键获取对应的值(cjson对象)
  15. /* 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. */
  16. extern const char *cJSON_GetErrorPtr(void); //获取错误字符串

 

要解析的json


   
   
  1. {
  2.     "semantic": {
  3.         "slots":    {
  4.             "name": "张三"
  5.         }
  6.     },
  7.     "rc":   0,
  8.     "operation":     "CALL",
  9.     "service":   "telephone",
  10.     "text": "打电话给张三"
  11. }

 


   
   
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "cJSON.h"
  4. void printJson(cJSON * root)//以递归的方式打印json的最内层键值对
  5. {
  6.     for( int i= 0; i<cJSON_GetArraySize(root); i++)   //遍历最外层json键值对
  7.     {
  8.         cJSON * item = cJSON_GetArrayItem(root, i);        
  9.         if(cJSON_Object == item->type)       //如果对应键的值仍为cJSON_Object就递归调用printJson
  10.             printJson(item);
  11.         else                                 //值不为json对象就直接打印出键和值
  12.         {
  13.             printf( "%s->", item-> string);
  14.             printf( "%s\n", cJSON_Print(item));
  15.         }
  16.     }
  17. }
  18. int main()
  19. {
  20.     char * jsonStr = "{\"semantic\":{\"slots\":{\"name\":\"张三\"}}, \"rc\":0, \"operation\":\"CALL\", \"service\":\"telephone\", \"text\":\"打电话给张三\"}";
  21.     cJSON * root = NULL;
  22.     cJSON * item = NULL; //cjson对象
  23.     root = cJSON_Parse(jsonStr);     
  24.     if (!root) 
  25.     {
  26.         printf( "Error before: [%s]\n",cJSON_GetErrorPtr());
  27.     }
  28.     else
  29.     {
  30.         printf( "%s\n", "有格式的方式打印Json:");           
  31.         printf( "%s\n\n", cJSON_Print(root));
  32.         printf( "%s\n", "无格式方式打印json:");
  33.         printf( "%s\n\n", cJSON_PrintUnformatted(root));
  34.         printf( "%s\n", "一步一步的获取name 键值对:");
  35.         printf( "%s\n", "获取semantic下的cjson对象:");
  36.         item = cJSON_GetObjectItem(root, "semantic"); //
  37.         printf( "%s\n", cJSON_Print(item));
  38.         printf( "%s\n", "获取slots下的cjson对象");
  39.         item = cJSON_GetObjectItem(item, "slots");
  40.         printf( "%s\n", cJSON_Print(item));
  41.         printf( "%s\n", "获取name下的cjson对象");
  42.         item = cJSON_GetObjectItem(item, "name");
  43.         printf( "%s\n", cJSON_Print(item));
  44.         printf( "%s:", item-> string);   //看一下cjson对象的结构体中这两个成员的意思
  45.         printf( "%s\n", item->valuestring);
  46.                         
  47.         printf( "\n%s\n", "打印json所有最内层键值对:");
  48.         printJson(root);
  49.     }
  50.     return 0;    
  51. }

 

  二、构造json:

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

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


   
   
  1. xtern cJSON *cJSON_CreateObject(void);
  2. extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
  3. extern cJSON *cJSON_CreateNull(void);
  4. extern cJSON *cJSON_CreateTrue(void);
  5. extern cJSON *cJSON_CreateFalse(void);
  6. extern cJSON *cJSON_CreateBool(int b);
  7. extern cJSON *cJSON_CreateNumber(double num);
  8. extern cJSON *cJSON_CreateString(const char *string);
  9. extern cJSON *cJSON_CreateArray(void);
  10. extern cJSON *cJSON_CreateObject(void);

 例子:     要构建的json:


   
   
  1. "semantic": {
  2.         "slots":    {
  3.             "name": "张三"
  4.         }
  5.     },
  6.     "rc":   0,
  7.     "operation":     "CALL",
  8.     "service":   "telephone",
  9.     "text": "打电话给张三"
  10. }

   
   
  1. #include <stdio.h>
  2. #include "cJSON.h"
  3. int main()
  4. {
  5.     cJSON * root =  cJSON_CreateObject();
  6.     cJSON * item =  cJSON_CreateObject();
  7.     cJSON * next =  cJSON_CreateObject();
  8.     cJSON_AddItemToObject(root, "rc", cJSON_CreateNumber( 0)); //根节点下添加
  9.     cJSON_AddItemToObject(root, "operation", cJSON_CreateString( "CALL"));
  10.     cJSON_AddItemToObject(root, "service", cJSON_CreateString( "telephone"));
  11.     cJSON_AddItemToObject(root, "text", cJSON_CreateString( "打电话给张三"));
  12.     cJSON_AddItemToObject(root, "semantic", item); //root节点下添加semantic节点
  13.     cJSON_AddItemToObject(item, "slots", next); //semantic节点下添加item节点
  14.     cJSON_AddItemToObject(next, "name", cJSON_CreateString( "张三")); //添加name节点
  15.     printf( "%s\n", cJSON_Print(root));
  16.     return 0;
  17. }

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值