rapidjson使用介绍
- 2016-05-09 22:05:00
- admin
- 原创 3679
一、rapidjson使用介绍
1、A fast JSON parser/generator for C++ with both SAX/DOM style API;
2、特点是解析速度最快,且只需要头文件;
3、官方网址:https://rapidjson.org/zh-cn/
4、代码示例:rapidjson.cpp
void parseAbnormalJSON()
{
Document d;
d.Parse("");
prnBool(d.IsNull());//true
prnBool(d.HasParseError());//true
d.Parse("{");
prnBool(d.IsNull());//true
prnBool(d.HasParseError());//true
//d.Parse(NULL); crash
}
void parseJSONObject()
{
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
prnBool(d.IsObject());//true
//s = d["unknown"]; crash
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
cout << buffer.GetString() << endl;
}
void parseJSONArray()
{
const char* json = "[2,3,5,7]";
Document d;
d.Parse(json);
prnBool(d.IsArray());//true
for (SizeType idx = 0; idx < d.Size(); ++idx)
printf("arr[%d]=%d\n", idx, d[idx]);
}
void findMember()
{
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
Value::ConstMemberIterator itr = d.FindMember("project");
if (itr != d.MemberEnd())
printf("%s\n", itr->value.GetString());
}
void createObjectAndArray()
{
Document o;
Document::AllocatorType &alloc = o.GetAllocator();
o.SetObject();
o.AddMember("name", "feinen", alloc);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
o.Accept(writer);
cout << buffer.GetString() << endl;
Document a;
Document::AllocatorType &alloc2 = o.GetAllocator();
a.SetArray();
a.PushBack("red", alloc2);
buffer.Clear(); //清除数据
writer.Reset(buffer); //清除状态
a.Accept(writer);
cout << buffer.GetString() << endl;
}