GitHub下载地址:rapidjson
特性参考官方说明:高效的 C++ JSON 解析/生成器
或者:RapidJSON 文档
解压后的目录为:
rapidjson-master
|-- CHANGELOG.md
|-- CMakeLists.txt
|-- CMakeModules
|-- RapidJSON.pc.in
|-- RapidJSONConfig.cmake.in
|-- RapidJSONConfigVersion.cmake.in
|-- appveyor.yml
|-- bin
|-- contrib
|-- doc
|-- docker
|-- example
|-- include
|-- include_dirs.js
|-- library.json
|-- license.txt
|-- package.json
|-- rapidjson.autopkg
|-- readme.md
|-- readme.zh-cn.md
|-- test
|-- thirdparty
`-- travis-doxygen.sh
使用的话只需要将 include 文件夹拷贝出来即可:
include
`-- rapidjson
|-- allocators.h
|-- cursorstreamwrapper.h
|-- document.h
|-- encodedstream.h
|-- encodings.h
|-- error
|-- filereadstream.h
|-- filewritestream.h
|-- fwd.h
|-- internal
|-- istreamwrapper.h
|-- memorybuffer.h
|-- memorystream.h
|-- msinttypes
|-- ostreamwrapper.h
|-- pointer.h
|-- prettywriter.h
|-- rapidjson.h
|-- reader.h
|-- schema.h
|-- stream.h
|-- stringbuffer.h
`-- writer.h
测试代码目录结构:
|-- jsonfile.txt
|-- makefile
|-- rapidjson
`-- test.cpp
test.cpp :
#include "rapidjson/document.h"
#include <iostream>
#include <fstream>
using namespace rapidjson;
using namespace std;
int main()
{
char*buffer = NULL;
// 读取文件的文本
filebuf *pbuf;
ifstream filestr;
long size;
// 要读入整个文件,必须采用二进制打开
filestr.open ("jsonfile.txt", ios::binary);
if (!filestr)
return -1;
// 获取filestr对应buffer对象的指针
pbuf=filestr.rdbuf();
// 调用buffer对象方法获取文件大小
size=pbuf->pubseekoff (0,ios::end,ios::in);
pbuf->pubseekpos (0,ios::in);
// 分配内存空间
buffer=new char[size];
// 获取文件内容
pbuf->sgetn (buffer,size);
filestr.close();
//开始解析json
Document document;
document.Parse(buffer);
if (document.HasParseError())
{
return -1;
}
assert(document.IsObject());
for (rapidjson::Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); iter++)
{
if (iter->name.IsString())
{
switch(iter->value.GetType())
{
case 0:
cout << "null" <<endl;
//cout << iter->value.IsNull() <<endl;
break;
case 1:
cout << "false" <<endl;
break;
case 2:
cout << "true" <<endl;
break;
case 3:
cout << "object" <<endl;
break;
case 4:
cout << "array" <<endl;
break;
case 5:
cout << "string" <<endl;
break;
case 6:
cout << "num" <<endl;
break;
default:
cout << "unknown type" <<endl;
}
}
}
delete []buffer;
return 0;
}
jsonfile.txt:
{
"hello": "world",
"t": true ,
"f": false,
"n": null,
"i": 123,
"pi": 3.1416,
"a": [1, 2, 3, 4]
}
输出:
string
true
false
null
num
num
array
参考: