大佬教程收集整理的这篇文章主要介绍了使用 CJSON 在C语言中进行 JSON 的创建和解析的实例讲解,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
本文用代码简单介绍cjson的使用方法,1)创建json,从json中获取数据。2)创建json数组和解析json数组
1、创建json,从json中获取数据
1 #include <stdio.h> 2 #include "cJSON.h" 3 4 char * makeJson() 5 { 6 cJSON * pJsonRoot = NULL; 7 8 pJsonRoot = cJSON_CreateObject(); 9 if(NULL == pJsonRoot) 10 { 11 //error happend here 12 return NULL; 13 } 14 cJSON_AddStringToObject(pJsonRoot,Hello",0); line-height:1.5!important">Hello world"); 15 cJSON_AddnumberToObject(pJsonRoot,0); line-height:1.5!important">number10010); 16 cJSON_AddBoolToObject(pJsonRoot,0); line-height:1.5!important">bool1); 17 cJSON * pSubJson = NULL; 18 pSubJson = cJSON_CreateObject(); 19 if(NULL == pSubJson) 20 { 21 create object faild,exit 22 cJSON_delete(pJsonRoot); 23 24 } 25 cJSON_AddStringToObject(pSubJson,0); line-height:1.5!important">subjsonobja sub json String 26 cJSON_AddItemToObject(pJsonRoot,0); line-height:1.5!important">subobj",pSubJson); 27 28 char * p = cJSON_Print(pJsonRoot); 29 else use : 30 char * p = cJSON_PrintUnformatted(pJsonRoot); 31 if(NULL == p) 32 { 33 convert json list to String faild,exit 34 because sub json pSubJson han been add to pJsonRoot,so just delete pJsonRoot,if you also delete pSubJson,it will coredump,and error is : double free 35 cJSON_delete(pJsonRoot); 36 37 } 38 free(p); 39 40 cJSON_delete(pJsonRoot); 41 42 return p; 43 } 44 45 void parseJson(char * pMsg) 46 { 47 if(NULL == pMsg) 48 { 49 return; 50 } 51 cJSON * pJson = cJSON_Parse(pMsg); 52 if(NULL == pJson) 53 { 54 parse faild,return 55 return ; 56 } 57 58 get String from json 59 cJSON * pSub = cJSON_GetObjectItem(pJson,128); line-height:1.5!important"> 60 if(NULL == pSub) 61 { 62 get object named "Hello" faild 63 } 64 printf(obj_1 : %s\n:rgb(128,pSub->valueString); 65 66 get number from json 67 pSub = cJSON_GetObjectItem(pJson,128); line-height:1.5!important"> 68 69 { 70 get number from json faild 71 } 72 printf(obj_2 : %d\n:rgb(128,pSub->valueint); 73 74 get bool from json 75 pSub = cJSON_GetObjectItem(pJson,128); line-height:1.5!important"> 76 77 { 78 get bool from json faild 79 } 80 printf(obj_3 : %d\n 81 82 get sub object 83 pSub = cJSON_GetObjectItem(pJson,128); line-height:1.5!important"> 84 85 { 86 get sub object faild 87 } 88 cJSON * pSubSub = cJSON_GetObjectItem(pSub,128); line-height:1.5!important"> 89 if(NULL == pSubSub) 90 { 91 get object from subject object faild 92 } 93 printf(sub_obj_1 : %s\n:rgb(128,pSubSub->valueString); 94 95 cJSON_delete(pJson); 96 } 97 98 int main() 99 { 100 char * p = makeJson(); 101 102 { 103 return 0; 104 } 105 printf(%s\n:rgb(128,p); 106 parseJson(p); 107 free(p); //千万不要忘记释放内存呀,cJSON_Print()函数或者cJSON_PrintUnformatted()产生的内存,使用free(char *)进行释放 108 109 }
centos下编译通过,运行结果如下
以上是大佬教程为你收集整理的使用 CJSON 在C语言中进行 JSON 的创建和解析的实例讲解全部内容,希望文章能够帮你解决使用 CJSON 在C语言中进行 JSON 的创建和解析的实例讲解所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。