cJSON调用方法

前端之家收集整理的这篇文章主要介绍了cJSON调用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


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

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


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


比如你有一个json数据


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

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

cJSON*root=cJSON_Parse(my_json_string);

2:获取某个元素

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

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

char*rendered=cJSON_Print(root);

cJSON_Delete(root);






构建一个json结构体

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

猜你在找的Json相关文章