Json---Windows下使用Jsoncpp
上述Json解析使用的是Jsoncpp,要使用Jsoncpp,得做如下几步的配置:
1.
首先从http://sourceforge.net/projects/jsoncpp/下载,压缩包大约105k。
2.
解压之后,进入 jsoncpp-src-0.5.0\makefiles\vs71 打开 jsoncpp.sln
3.
debug编译lib_json 项目,会在 jsoncpp-src-0.5.0\build\vs71\debug\lib_json 下生成 json_vc71_libmtd.lib
release编译lib_json 项目
项目属性->C/C++ ->输出文件->汇编输出 要设置成 无列表 (否则,在自己项目中引用生成的 json_vc71_libmt.lib 编译时会报错)。
会在 jsoncpp-src-0.5.0\build\vs71\release\lib_json 下生成 json_vc71_libmt.lib
4
在自己的项目中,引用 jsoncpp-src-0.5.0\include\json 下的头文件,和相应的 json_vc71_libmt.lib(debug 版) 或 json_vc71_libmt.lib(release 版)。
就可以开始使用了。
Demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include <fstream> #include "json.h" using namespace std; int JsonRead() { ifstream ifs; ifs.open( "testR.json" ); Json::Reader reader; Json::Value value; if (!reader.parse(ifs,value, false )) { return -1; } if (value.isObject()) //单个json串,格式:{"age":23,"name":"往事随风"} { string name = value[ "name" ].asString(); if (value[ "name" ].isString()) { name = value[ "name" ].asString(); cout << "name:" << name << endl; } int age = value[ "age" ].asInt(); if (value[ "age" ].isInt()) { age = value[ "age" ].asInt(); cout << "age:" << age << endl; } int aaa = value[ "aaa" ].asInt(); //value 没有 "aaa" 这个key的数据时,会给 aaa 赋初值 0 } else if (value.isArray()) //json数组,格式:[{"age":23,"name":"往事随风"}] { cout << value.size() << endl; for ( int i = 0; i < value.size(); i++) { string name = value[i][ "name" ].asString(); if (value[i][ "name" ].isString()) { name = value[i][ "name" ].asString(); cout << "name:" << name << endl; } int age = value[i][ "age" ].asInt(); if (value[i][ "age" ].isInt()) { age = value[i][ "age" ].asInt(); cout << "age:" << age << endl; } int aaa = value[i][ "aaa" ].asInt(); } } getchar (); return 0; } int JsonWrite() { Json::Value root; Json::FastWriter writer; Json::Value person; person[ "name" ] = "往事随风" ; person[ "age" ] = 23; //root.append(person); string json_file = writer.write(person); //单个json串,格式:{"age":23,"name":"往事随风"} //string json_file = writer.write(root); //json数组,格式:[{"age":23,"name":"往事随风"}] ofstream ofs; ofs.open( "testW.json" ); ofs<<json_file; getchar (); return 0; } int main() { JsonRead(); JsonWrite(); return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)