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

cJSON调用方法

发布时间:2020-12-16 19:18:02 所属栏目:百科 来源:网络整理
导读:?? 我使用的是cJSON:http://sourceforge.net/projects/cjson/ 先看json的数据结构 c中没有对象,所以json数据是采用链表存储的 typedef struct cJSON{ struct cJSON*next,*prev; //数组对象数据中用到 struct cJSON*child; //数组和对象中指向子数组对象或值
??

我使用的是cJSON:http://sourceforge.net/projects/cjson/

先看json的数据结构
c中没有对象,所以json数据是采用链表存储的


  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数据


  1. {
  2. "name":"Jack("Bee")Nimble",
  3. "format":{
  4. "type":"rect",
  5. "width":1920,
  6. "height":1080,
  7. "interlace":false,
  8. "framerate":24
  9. }
  10. }

那么你可以
1:讲字符串解析成json结构体。

cJSON*root=cJSON_Parse(my_json_string);

2:获取某个元素

  1. cJSON*format=cJSON_GetObjectItem(root,"format");
  2. intframerate=cJSON_GetObjectItem(format,"framerate")->valueint;

3:讲json结构体转换成字符串

char*rendered=cJSON_Print(root);

cJSON_Delete(root);






构建一个json结构体

C代码
  1. cJSON*root,*fmt;
  2. root=cJSON_CreateObject();
  3. cJSON_AddItemToObject(root,"name",cJSON_CreateString("Jack("Bee")Nimble"));
  4. cJSON_AddItemToObject(root,"format",fmt=cJSON_CreateObject());
  5. cJSON_AddStringToObject(fmt,"type","rect");
  6. cJSON_AddNumberToObject(fmt,"width",1920);
  7. cJSON_AddNumberToObject(fmt,"height",1080);
  8. cJSON_AddFalseToObject(fmt,"interlace");
  9. cJSON_AddNumberToObject(fmt,"framerate",24);

(编辑:李大同)

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

    推荐文章
      热点阅读