一、概述
作用:可以在c程序中方便的进行json字符串的解析及生成
二、代码示例
//组装一个json串 void CJsonTest::valueToJsonObject() { cJSON* root, * fmt; char* out; root = cJSON_CreateObject();//创建一个obj(申请了堆内存记得释放) cJSON_AddItemToObject(root, "name", cJSON_CreateString("luoluoyang")); cJSON_AddNumberToObject(root, "age", 6); cJSON_AddItemToObject(root, "address", fmt = cJSON_CreateObject());//创建一个新的Object放入到root中 //给新的对象增加属性 cJSON_AddStringToObject(fmt, "addr", "he nan"); cJSON_AddNumberToObject(fmt, "width", 10); cJSON_AddNumberToObject(fmt, "height", 10); cJSON_AddFalseToObject(fmt, "interlace"); cJSON_AddTrueToObject(fmt, "isOpen"); cJSON_AddNumberToObject(fmt, "frame_rate", 24); //将cJSON转为json字符串输出 out = cJSON_Print(root); cout << out << endl; //释放申请的内存空间 cJSON_Delete(root); free(out); } //解析json串 void CJsonTest::parseJsonObject() { //组装json字符串(用于最后的测试) char* jsonStr; cJSON* root; root = cJSON_CreateObject();//初始化cJSON,这一步需要申请内存,记得清理 cJSON_AddStringToObject(root, "name", "LOL");//添加一个name属性,value是LOL cJSON* heros, * countrys; heros = cJSON_AddArrayToObject(root, "heros");//向root中添加一个heros数组 //向数组中添加元素 cJSON_AddItemToArray(heros, cJSON_CreateString("Tom")); cJSON_AddItemToArray(heros, cJSON_CreateString("Jack")); countrys = cJSON_AddArrayToObject(root, "countrys");//再创一个数组 cJSON* obj = cJSON_CreateObject();//创建一个object cJSON_AddStringToObject(obj, "name", "xiao ming"); cJSON_AddNumberToObject(obj, "age", 10); cJSON_AddItemToArray(countrys, obj);//将obj添加进数组 jsonStr = cJSON_Print(root); cout << jsonStr << endl; cJSON_Delete(root); //解析json字符串 cJSON* parseObj = cJSON_Parse(jsonStr); char* rootName = cJSON_GetObjectItem(parseObj, "name")->valuestring; cout << "rootName:" << rootName << endl; //从根节点中拿到数组 cJSON* arrStr = cJSON_GetObjectItem(parseObj, "heros"); //拿到json数组的长度 int arrLen = cJSON_GetArraySize(arrStr); //循环从数组中取出item for (int i = 0;i < arrLen;i++) { char* nameStr = cJSON_GetArrayItem(arrStr, i)->valuestring; cout << "nameStr:" << nameStr << endl; } //从object中取出对象数组 cJSON* myCountrys = cJSON_GetObjectItem(parseObj, "countrys"); cout << "myCountrys:" << cJSON_Print(myCountrys) << endl; cout << "------------解析jsonObject----------" << endl; //获取对象数组的长度 int countryLen = cJSON_GetArraySize(myCountrys); //循环遍历对象数组,并解析里面对象的value值 for (int i = 0;i < countryLen;i++) { cJSON* myObj = cJSON_GetArrayItem(myCountrys, i); char* itemName = cJSON_GetObjectItem(myObj, "name")->valuestring; cout << "itemName:" << itemName << endl; int myAge = cJSON_GetObjectItem(myObj, "age")->valueint; cout << "myAge:" << myAge << endl; } //释放开辟的内存 if (parseObj) { cJSON_Delete(parseObj); } free(jsonStr); }
标签:cout,cJSON,fmt,AddNumberToObject,json,解析,root From: https://www.cnblogs.com/tony-yang-flutter/p/18318635