本文详细记录了作者在使用json-cpp进行JSON数据处理过程中的经验和技巧。文章首先介绍了json-cpp库的基本概念和功能包括其在C程序中处理JSON数据的优势。接着作者通过实例展示了如何使用json-cpp进行JSON数据的解析和生成包括读取JSON文件、构建JSON对象、访问和修改JSON数据等关键步骤。此外文章还分享了一些使用json-cpp时可能遇到的问题及解决方案并给出了一些性能优化和错误处理的建议。最后总结了json-cpp库的特点和使用体验为其他开发者在使用json-cpp时提供了有益的参考。1. 介绍Json-cpp是一个跨平台的轻量级的读取Json文件的C开源库2. 安装可以自行下载编译安装下载地址json-cpp download | SourceForge.net也可以使用命令直接安装sudo apt install libjsoncpp-dev3. CMake编写find_package(jsoncpp CONFIG REQUIRED) include_directories(${JSON_INC_PATH}) target_link_libraries(${PROJECT_NAME} jsoncpp_lib)4. 使用说明4.1. 头文件#include jsoncpp/json/json.h4.2. 从字符串解析jsonconst char* str {\uploadid\: \UP000000\,\code\: 100,\msg\: \\,\files\: \\}; Json::Reader reader; Json::Value root; if (reader.parse(str, root)) // reader将Json字符串解析到rootroot将包含Json里所有子元素 { std::string upload_id root[uploadid].asString(); // 访问节点upload_id UP000000 int code root[code].asInt(); // 访问节点code 100 }4.3. 从文件解析jsonvoid ParseCalibrationFile(const std::string file_path) { Json::Reader reader; // 解析json用Json::Reader Json::Value node; // Json::Value是一种很重要的类型可以代表任意类型。如int, string, object, array std::fstream file(file_path, std::ios::in); if (reader.parse(file, node, false)) { std::string code; if (!node[files].isNull()) { // 访问节点Access an object value by name, create a null member if it does not exist. code node[uploadid].asString(); } code node.get(uploadid, null).asString(); // 访问节点Return the member named key if it exist, defaultValue otherwise. int file_size node[files].size(); // 得到files的数组个数 for (int i 0; i file_size; i) { // 遍历数组 Json::Value val_image node[files][i][images]; int image_size val_image.size(); for (int j 0; j image_size; j) { std::string type val_image[j][type].asString(); std::string url val_image[j][url].asString(); printf(type : %s, url : %s \n, type.c_str(), url.c_str()); } } const Json::Value bboxes_node node[bboxes]; for (const Json::Value rectangle : bboxes_node) { cv::Point2d point1(translation_array[0].asDouble(), translation_array[1].asDouble()); } } file.close(); }#include jsoncpp/json/json.h #include iostream #include string typedef Json::Writer JsonWriter; typedef Json::Reader JsonReader; typedef Json::Value JsonValue; using namespace std; void print_json(JsonValue data) { JsonValue::Members mem data.getMemberNames(); for (auto iter mem.begin(); iter ! mem.end(); iter) { cout *iter \t: ; if (data[*iter].type() Json::objectValue) { cout endl; print_json(data[*iter]); } else if (data[*iter].type() Json::arrayValue) { cout endl; auto cnt data[*iter].size(); for (auto i 0; i cnt; i) { print_json(data[*iter][i]); } } else if (data[*iter].type() Json::stringValue) { cout data[*iter].asString() endl; } else if (data[*iter].type() Json::realValue) { cout data[*iter].asDouble() endl; } else if (data[*iter].type() Json::uintValue) { cout data[*iter].asUInt() endl; } else { cout data[*iter].asInt() endl; } } return; } int main() { std::string szJson { \weatherinfo\:{\city\:\北京\, \cityid\ : \101010100\, \temp\ : \18\, \WD\ : \东南风\, \WS\ : \1级\, \SD\ : \17 % \, \WSE\ : \1\, \time\ : \17:05\, \isRadar\ : \1\, \Radar\ : \JC_RADAR_AZ9010_JB\, \njd\ : \这是什么\, \qy\ : \1011\, \rain\ : \0\} }; //解析json数据 JsonReader reader; JsonValue value; if (!reader.parse(szJson, value)) { return 0; } //遍历键值 print_json(value); system(pause); return 0; }4.4. 向文件中插入jsonvoid WriteJsonData(const char* filename) { Json::Reader reader; Json::Value root; // Json::Value是一种很重要的类型可以代表任意类型。如int, string, object, array std::ifstream is; is.open (filename, std::ios::binary); if (reader.parse(is, root)) { Json::Value arrayObj; // 构建对象 Json::Value new_item, new_item1; new_item[date] 2011-11-11; new_item1[time] 11:11:11; arrayObj.append(new_item); // 插入数组成员 arrayObj.append(new_item1); // 插入数组成员 int file_size root[files].size(); for(int i 0; i file_size; i) { root[files][i][exifs] arrayObj; // 插入原json中 } std::string out root.toStyledString(); // 输出无格式json字符串 Json::FastWriter writer; std::string strWrite writer.write(root); std::ofstream ofs; ofs.open(test_write.json); ofs strWrite; ofs.close(); } is.close(); }4.5. 序列化json字符串先构建一个Json对象此Json对象中含有数组然后把Json对象序列化成字符串Json::Value root; Json::Value arrayObj; Json::Value item; for (int i0; i10; i) { item[key] i; arrayObj.append(item); } root[key1] “value1″; root[key2] “value2″; root[array] arrayObj; root.toStyledString(); std::string out root.toStyledString(); std::cout out std::endl;4.6. 反序列化jsonstd::string strValue “{\”key1\”:\”value1\”,\”array\”:[{\key2\:\value2\},{\key2\:\value3\},{\key2\:\value4\}]}”; Json::Reader reader; Json::Value value; if (reader.parse(strValue, value)) { std::string out value[key1].asString(); std::cout out std::endl; const Json::Value arrayObj value[array]; for (int i0; iarrayObj.size(); i) { out arrayObj[i][key2].asString(); std::cout out; if (i ! arrayObj.size() – 1) { std::cout std::endl; } } }4.7. 删除json子对象std::string strContent {\key\:\1\,\name\:\test\}; Json::Reader reader; Json::Value value; if (reader.parse(strContent, value)) { Json::Value rootvalue; root.removeMember(key); printf(%s \n,root.toStyledString().c_str()); }4.8. 利用jsoncpp将json字符串转换为Vectorconst char * jsongroupinfo[{/groupId/ :946838524,/groupname/ :/bababa/, /mask/:1,/parentid/:946755072}]; Json::Reader reader; Json::Value json_object; if (!reader.parse(jsongroupinfo, json_object)) { return parse jsonstr error; } SUserChggroup sucg; VECTOR SUserChggroup m_groupInfo; for(int i 0; i json_object.size(); i ) { Json::Value current json_object[i]; sucg.m_groupId current[groupId].asInt(); sucg.m_groupName current[groupname].asString(); sucg.m_mask current[mask].asInt(); sucg.m_parentId current[parentid].asInt(); m_groupInfo.push_back(sucg); }简而言之就是把它变成解析成一个个对象再将对象存储到vector中。std::string strRtn {success:true,user:{id:6,username:wq,type:admin,membership:{type:paid,expiredAt:2019-07-28T16:00:00.000Z}},token:8de57200-3235-11e8-83f1-9739d2f0386f}; std::string strToken; Json::Reader reader; //解析json用Json::Reader Json::Value value; //可以代表任意类型 if (reader.parse(strRtn.c_str(),strRtn.c_str()strRtn.size(), value)) { if (value[success].asBool()) { strToken value[token].asCString(); } }参考文献CMakeLists编写和测试实例_杂七杂八的的博客-CSDN博客_cmakelist jsoncppC解析Json---Json-cpp使用_芒种、的博客-CSDN博客_json2cppJSONCPP遍历JSON数据_hellokandy的博客-CSDN博客_jsoncpp遍历json数据