当前位置:   article > 正文

c语言-json开源库cJSON的使用

json开源代码c语言

一、cJSON的介绍

    cJSON是一个开源的JSON解析器,用于解析JSON数据。它是由纯C语言实现,因此跨平台性好,移植简单。

下载地址:

  1. https://github.com/DaveGamble/cJSON.git
  2. https://gitee.com/du-yueqiang/cJSON?_from=gitee_search

76e3eb40657861c9bf0283952416c232.png

e9df5f9992940cf144d575783f08594d.png

40d145c2fd0d4b4c99f7aabf262f808b.png

二、移植方法

    cJSON只有一个cjson.c和cjson.h文件,可以很方便地集成到其他项目中。cJSON支持将JSON数据解析为cJSON对象,也支持将cJSON对象转换为JSON数据。cJSON的使用非常简单,只需要包含cjson.h头文件,然后调用相应的API即可完成JSON数据的解析和生成。

三、测试代码

  1. //根据官方代码修改,创建json格式数据(字符串、整形、数组)
  2. //增加了json数据解析功能
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "cJSON.h"
  7. /* Used by some code below as an example datatype. */
  8. struct record
  9. {
  10. const char *precision;
  11. double lat;
  12. double lon;
  13. const char *address;
  14. const char *city;
  15. const char *state;
  16. const char *zip;
  17. const char *country;
  18. };
  19. /* Create a bunch of objects as demonstration. */
  20. static int print_preallocated(cJSON *root)
  21. {
  22. /* declarations */
  23. char *out = NULL;
  24. char *buf = NULL;
  25. char *buf_fail = NULL;
  26. size_t len = 0;
  27. size_t len_fail = 0;
  28. /* formatted print */
  29. out = cJSON_Print(root);
  30. /* create buffer to succeed */
  31. /* the extra 5 bytes are because of inaccuracies when reserving memory */
  32. len = strlen(out) + 5;
  33. buf = (char*)malloc(len);
  34. if (buf == NULL)
  35. {
  36. printf("Failed to allocate memory.\n");
  37. exit(1);
  38. }
  39. /* create buffer to fail */
  40. len_fail = strlen(out);
  41. buf_fail = (char*)malloc(len_fail);
  42. if (buf_fail == NULL)
  43. {
  44. printf("Failed to allocate memory.\n");
  45. exit(1);
  46. }
  47. /* Print to buffer */
  48. if (!cJSON_PrintPreallocated(root, buf, (int)len, 1)) {
  49. printf("cJSON_PrintPreallocated failed!\n");
  50. if (strcmp(out, buf) != 0) {
  51. printf("cJSON_PrintPreallocated not the same as cJSON_Print!\n");
  52. printf("cJSON_Print result:\n%s\n", out);
  53. printf("cJSON_PrintPreallocated result:\n%s\n", buf);
  54. }
  55. free(out);
  56. free(buf_fail);
  57. free(buf);
  58. return -1;
  59. }
  60. /* success */
  61. printf("%s\n", buf);
  62. /* force it to fail */
  63. if (cJSON_PrintPreallocated(root, buf_fail, (int)len_fail, 1)) {
  64. printf("cJSON_PrintPreallocated failed to show error with insufficient memory!\n");
  65. printf("cJSON_Print result:\n%s\n", out);
  66. printf("cJSON_PrintPreallocated result:\n%s\n", buf_fail);
  67. free(out);
  68. free(buf_fail);
  69. free(buf);
  70. return -1;
  71. }
  72. free(out);
  73. free(buf_fail);
  74. free(buf);
  75. return 0;
  76. }
  77. /* Create a bunch of objects as demonstration. */
  78. static void create_objects(void)
  79. {
  80. /* declare a few. */
  81. cJSON *root = NULL;
  82. cJSON *fmt = NULL;
  83. cJSON *img = NULL;
  84. cJSON *thm = NULL;
  85. cJSON *fld = NULL;
  86. int i = 0;
  87. int n;
  88. /* Our "days of the week" array: */
  89. const char *strings[7] =
  90. {
  91. "Sunday",
  92. "Monday",
  93. "Tuesday",
  94. "Wednesday",
  95. "Thursday",
  96. "Friday",
  97. "Saturday"
  98. };
  99. /* Our matrix: */
  100. int numbers[3][3] =
  101. {
  102. {0, -1, 0},
  103. {1, 0, 0},
  104. {0 ,0, 1}
  105. };
  106. /* Our "gallery" item: */
  107. int ids[4] = { 116, 943, 234, 38793 };
  108. /* Our array of "records": */
  109. struct record fields[2] =
  110. {
  111. {
  112. "zip",
  113. 37.7668,
  114. -1.223959e+2,
  115. "",
  116. "SAN FRANCISCO",
  117. "CA",
  118. "94107",
  119. "US"
  120. },
  121. {
  122. "zip",
  123. 37.371991,
  124. -1.22026e+2,
  125. "",
  126. "SUNNYVALE",
  127. "CA",
  128. "94085",
  129. "US"
  130. }
  131. };
  132. volatile double zero = 0.0;
  133. /* Here we construct some JSON standards, from the JSON site. */
  134. /* Our "Video" datatype: */
  135. root = cJSON_CreateObject();
  136. cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
  137. cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());
  138. cJSON_AddStringToObject(fmt, "type", "rect");
  139. cJSON_AddNumberToObject(fmt, "width", 1920);
  140. cJSON_AddNumberToObject(fmt, "height", 1080);
  141. cJSON_AddFalseToObject (fmt, "interlace");
  142. cJSON_AddNumberToObject(fmt, "frame rate", 24);
  143. /* Print to text */
  144. if (print_preallocated(root) != 0) {
  145. cJSON_Delete(root);
  146. exit(EXIT_FAILURE);
  147. }
  148. cJSON *name=cJSON_GetObjectItem(root,"name");
  149. if (cJSON_IsString(name) && (name->valuestring != NULL))
  150. {
  151. printf("name is \"%s\"\n", name->valuestring);
  152. }
  153. cJSON *format=cJSON_GetObjectItem(root,"format");
  154. if (cJSON_IsObject(format) && (format != NULL))
  155. {
  156. if (print_preallocated(format) != 0)
  157. {
  158. cJSON_Delete(root);
  159. exit(EXIT_FAILURE);
  160. }
  161. cJSON *type=cJSON_GetObjectItem(format,"type");
  162. if (cJSON_IsString(type) && (type->valuestring != NULL))
  163. {
  164. printf("type is \"%s\"\n", type->valuestring);
  165. }
  166. cJSON *width=cJSON_GetObjectItem(format,"width");
  167. if (cJSON_IsNumber(width))
  168. {
  169. printf("width is %d\n", width->valueint);
  170. }
  171. cJSON *interlace=cJSON_GetObjectItem(format,"interlace");
  172. if (cJSON_IsBool(interlace))
  173. {
  174. printf("interlace is %d\n", interlace->valueint);
  175. }
  176. }
  177. cJSON_Delete(root);
  178. /* Our "days of the week" array: */
  179. root = cJSON_CreateStringArray(strings, 7);
  180. if (print_preallocated(root) != 0) {
  181. cJSON_Delete(root);
  182. exit(EXIT_FAILURE);
  183. }
  184. n=cJSON_GetArraySize(root);
  185. cJSON *day;
  186. for(i=0;i<n;i++)
  187. {
  188. day=cJSON_GetArrayItem(root,i);
  189. if (cJSON_IsString(day) && (day->valuestring != NULL))
  190. {
  191. printf("day is \"%s\"\n", day->valuestring);
  192. }
  193. }
  194. cJSON_Delete(root);
  195. /* Our matrix: */
  196. root = cJSON_CreateArray();
  197. for (i = 0; i < 3; i++)
  198. {
  199. cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3));
  200. }
  201. /* cJSON_ReplaceItemInArray(root, 1, cJSON_CreateString("Replacement")); */
  202. if (print_preallocated(root) != 0) {
  203. cJSON_Delete(root);
  204. exit(EXIT_FAILURE);
  205. }
  206. n=cJSON_GetArraySize(root);
  207. cJSON *num;
  208. for(i=0;i<n;i++)
  209. {
  210. num=cJSON_GetArrayItem(root,i);
  211. int m=cJSON_GetArraySize(num);
  212. for(int k=0;k<m;k++)
  213. {
  214. cJSON *j=cJSON_GetArrayItem(num,k);
  215. if (cJSON_IsNumber(j) )
  216. {
  217. printf("day is %d\n", j->valueint);
  218. }
  219. }
  220. }
  221. cJSON_Delete(root);
  222. /* Our "gallery" item: */
  223. root = cJSON_CreateObject();
  224. cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject());
  225. cJSON_AddNumberToObject(img, "Width", 800);
  226. cJSON_AddNumberToObject(img, "Height", 600);
  227. cJSON_AddStringToObject(img, "Title", "View from 15th Floor");
  228. cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject());
  229. cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
  230. cJSON_AddNumberToObject(thm, "Height", 125);
  231. cJSON_AddStringToObject(thm, "Width", "100");
  232. cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4));
  233. if (print_preallocated(root) != 0) {
  234. cJSON_Delete(root);
  235. exit(EXIT_FAILURE);
  236. }
  237. cJSON_Delete(root);
  238. /* Our array of "records": */
  239. root = cJSON_CreateArray();
  240. for (i = 0; i < 2; i++)
  241. {
  242. cJSON_AddItemToArray(root, fld = cJSON_CreateObject());
  243. cJSON_AddStringToObject(fld, "precision", fields[i].precision);
  244. cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat);
  245. cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon);
  246. cJSON_AddStringToObject(fld, "Address", fields[i].address);
  247. cJSON_AddStringToObject(fld, "City", fields[i].city);
  248. cJSON_AddStringToObject(fld, "State", fields[i].state);
  249. cJSON_AddStringToObject(fld, "Zip", fields[i].zip);
  250. cJSON_AddStringToObject(fld, "Country", fields[i].country);
  251. }
  252. /* cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root, 1), "City", cJSON_CreateIntArray(ids, 4)); */
  253. if (print_preallocated(root) != 0) {
  254. cJSON_Delete(root);
  255. exit(EXIT_FAILURE);
  256. }
  257. cJSON_Delete(root);
  258. root = cJSON_CreateObject();
  259. cJSON_AddNumberToObject(root, "number", 1.0 / zero);
  260. if (print_preallocated(root) != 0) {
  261. cJSON_Delete(root);
  262. exit(EXIT_FAILURE);
  263. }
  264. cJSON_Delete(root);
  265. }
  266. int CJSON_CDECL main(void)
  267. {
  268. /* print the version */
  269. printf("Version: %s\n", cJSON_Version());
  270. /* Now some samplecode for building objects concisely: */
  271. create_objects();
  272. return 0;
  273. }

四、实验结果

执行之后,打印如下信息

  1. Version: 1.7.16
  2. {
  3. "name": "Jack (\"Bee\") Nimble",
  4. "format": {
  5. "type": "rect",
  6. "width": 1920,
  7. "height": 1080,
  8. "interlace": false,
  9. "frame rate": 24
  10. }
  11. }
  12. name is "Jack ("Bee") Nimble"
  13. {
  14. "type": "rect",
  15. "width": 1920,
  16. "height": 1080,
  17. "interlace": false,
  18. "frame rate": 24
  19. }
  20. type is "rect"
  21. width is 1920
  22. interlace is 0
  23. ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  24. day is "Sunday"
  25. day is "Monday"
  26. day is "Tuesday"
  27. day is "Wednesday"
  28. day is "Thursday"
  29. day is "Friday"
  30. day is "Saturday"
  31. [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
  32. day is 0
  33. day is -1
  34. day is 0
  35. day is 1
  36. day is 0
  37. day is 0
  38. day is 0
  39. day is 0
  40. day is 1
  41. {
  42. "Image": {
  43. "Width": 800,
  44. "Height": 600,
  45. "Title": "View from 15th Floor",
  46. "Thumbnail": {
  47. "Url": "http:/*www.example.com/image/481989943",
  48. "Height": 125,
  49. "Width": "100"
  50. },
  51. "IDs": [116, 943, 234, 38793]
  52. }
  53. }
  54. [{
  55. "precision": "zip",
  56. "Latitude": 37.7668,
  57. "Longitude": -122.3959,
  58. "Address": "",
  59. "City": "SAN FRANCISCO",
  60. "State": "CA",
  61. "Zip": "94107",
  62. "Country": "US"
  63. }, {
  64. "precision": "zip",
  65. "Latitude": 37.371991,
  66. "Longitude": -122.026,
  67. "Address": "",
  68. "City": "SUNNYVALE",
  69. "State": "CA",
  70. "Zip": "94085",
  71. "Country": "US"
  72. }]
  73. {
  74. "number": null
  75. }

438caaf00878679c2b083aa019fd8120.png

欢迎关注公众号:嵌入式学习与实践

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/460602
推荐阅读
相关标签
  

闽ICP备14008679号