RapidJSON使用简介

2016-05-09 22:05:00
admin
原创 2475
摘要:RapidJSON使用简介

一、什么是rapidjson?

A fast JSON parser/generator for C++ with both SAX/DOM style API(解析速度最快,并且只需要头文件)。

官网网址:http://rapidjson.org/zh-cn/


二、代码示例

下载地址:rapidjson.cpp


#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <stdlib.h>

using namespace std;
using namespace rapidjson;

void prnBool(int value)
{
if (value)
printf("true\n");
else
printf("false\n");
}

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;
}

int main()
{
parseAbnormalJSON();
parseJSONObject();
parseJSONArray();
findMember();
createObjectAndArray();

getchar();
return EXIT_SUCCESS;
}

发表评论
评论通过审核之后才会显示。