关于RapidJSON
rapidjson项目地址:https://github.com/miloyip/rapidjson
项目下载完成后,打开readme.md文件,查看项目说明。
RapidJSON is a header-only C++ library. Just copy the `include/rapidjson` folder to system or project's include path.
RapidJSON是一个只有头文件的C++ JSON库,只需要拷贝“include/rapidjson”目录到工程包含路径下即可使用。
文档说明地址:ttp://miloyip.github.io/rapidjson/
项目的构建
RapidJSON项目的构建需要使用一个工具,就是premake。
premake是一个跨平台项目构建工具。
premake下载地址:http://industriousone.com/premake/download
项目构建过程:
premake下载完成后,把premake4.exe文件解压到build目录下,点击premake.bat(Windows),如果是Linux/Mac则点击premake.sh,生成项目。
这里是windows平台下的项目构建,vs2005、vs2008、vs2010分别是不同版本的Visual Studio项目,打开解决方案后,可以看到一些RapidJSON库的使用示例。
RapidJSON的使用
1.拷贝include\rapidjson文件夹到项目路径下。
2.引入rapidjson库头文件
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
3.rapidjson的使用
const char* str = "{\"name\":\"xiaoming\",\"age\":18,\"job\":\"coder\",\"a\":{\"b\":1}}";
Document doc;
// 在DOM中解析json字符串
doc.Parse(str);
// 读取json数据
const Value& age = doc["age"];
printf("age=%d \n",age.GetInt());
// 修改json数据
age.SetString("data is change");
// 读取对象中的对象
const Value& b = doc["a"]["b"];
printf("b=%d \n",b.GetInt());
// 序列化
StringBuffer buff;
Writer
writer(buff);
doc.Accept(writer);
// 打印json字符串
printf(buff.GetString());
const char* name = "xiaoming";
int age = 18;
double height = 1.64;
StringBuffer buff;
Writer
writer(buff);
writer.StartObject();
writer.String("name");
//writer.String(name,10); 第二个参数用于设置写入字符串长度,如果超出字符串长度会有垃圾数据
writer.String(name);
writer.String("age");
writer.Int(age);
writer.String("height");
writer.Double(height);
// 数组
writer.String("arr");
writer.StartArray();
for (int i=0;i<5;++i)
{
writer.Int(i);
}
writer.EndArray();
writer.EndObject();
printf(buff.GetString());
const char* str = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\"}]}";
Document doc;
doc.Parse(str);
if (doc.HasParseError() == false)
{
const Value& employees = doc["employees"];
// rapidjson uses SizeType instead of size_t.
for (SizeType i = 0; i < employees.Size(); i++)
{
const Value& temp = employees[i];
printf("firstName=%sďźu008ClastName=%s \n",temp["firstName"].GetString(),temp["lastName"].GetString());
}
}else{
printf("parse error\n");
}
StringBuffer buff;
Writer
writer(buff);
writer.StartArray();
for (int i=0;i<5;++i)
{
writer.Int(i);
}
writer.EndArray();
printf("%s",buff.GetString());
测试工程地址:https://coding.net/u/linchaolong/p/RapidJSONTest/git