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

cJSON库使用教程

发布时间:2020-12-16 19:04:48 所属栏目:百科 来源:网络整理
导读:转载自:http://blog.csdn.net/geqiandebei/article/details/47977103 CSJON库基本数据格式 cJSON 定义 typedef struct cJSON{ struct cJSON*next,*prev; //数组对象数据中用到 struct cJSON*child; //数组和对象中指向子数组对象或值 int type; //元素的类

转载自:http://blog.csdn.net/geqiandebei/article/details/47977103

CSJON库基本数据格式 cJSON 定义

  1. typedefstructcJSON{
  2. structcJSON*next,*prev;//数组对象数据中用到
  3. structcJSON*child;//数组和对象中指向子数组对象或值
  4. inttype;//元素的类型,如是对象还是数组
  5. char*valuestring;//如果是字符串
  6. intvalueint;//如果是数值
  7. doublevaluedouble;//如果类型是cJSON_Number
  8. char*string;//Theitem'snamestring,ifthisitemisthechildof,orisinthelistofsubitemsofanobject.
  9. }cJSON;

构造JSON:

首先创建JSON主对象

[cpp] view plain copy print ?
  1. cJSON*root=cJSON_CreateObject();

类似的创建数组对象

?
    cJSON*array=cJSON_CreateArray();

向对象中增加(字符)节点

?
    cJSON_AddStringToObject(root,"名称","字符串");

向对象中增加对象(字符串、数组、数字)

?
    cJSON_AddItemToObject(root,cJSON_CreateString("邝东宇"));
  1. cJSON_AddItemToObject(root,"名称",cJSON_CreateNumber(100));

向数组中增加元素(元素类型不一定相同)

?

    <spanstyle="white-space:pre"></span>cJSON_AddItemToArray(array,cJSON_CreateString("Linux"));
  1. cJSON_AddItemToArray(array,cJSON_CreateNumber(26));

解析JSON:

首先获取字符串形式的JSON数据,例:存储于char data[1024];

获取JSON对象

?

    cJSON*root=cJSON_Parse(data);
获取指定名称的节点指针, ?
    cJSON*tmp=cJSON_GetObjectItem(root,"name");
解析数组,首先按上步获取数组指针 如 cJSON* array ?
    获取数组大小intsize=cJSON_GetArraySize(array)
  1. 获取数组元素cJSON*tmp=cJSON_GetArrayItem(array,1);//下标从0开始</span>


最后释放对象

?

    cJSON_Delete(root);
根据对象指针获取JSON字符串形式数据

?

    char*data=cJSON_Print(root);


附件cJSON库以及demo源码在本人CSDN资源中获取。

(编辑:李大同)

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

    推荐文章
      热点阅读