[rapidjson]_[C/C++]_[rapidjson库使用简单介绍]

 

场景:

1.cpp的json有很多,其中有jsoncpp等,rapidjson是一个比较好的选择,特别是开发跨平台应用时,因为它只有头文件.

2.在用cpp生成html网页时,通过json数据和javascript来控制页面内容是常见的方案.

3.官网: http://rapidjson.org/

4.例子貌似介绍的不够细.

 

这里例子生成数组集合的字符串。

 

#include <stdio.h>
#include <string>
#include <iostream>

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filestream.h"
#include "rapidjson/stringbuffer.h"

using namespace std;
using namespace rapidjson;

int main(int argc, char *argv[])
{
	printf("Lu//a\"\n");
	Document document;
	
	Document::AllocatorType& allocator = document.GetAllocator();
	Value contact(kArrayType);
	Value contact2(kArrayType);
	Value root(kArrayType);
	contact.PushBack("Lu//a\"", allocator).PushBack("Mio", allocator).PushBack("", allocator);
	contact2.PushBack("Lu// a", allocator).PushBack("Mio", allocator).PushBack("", allocator);
	root.PushBack(contact, allocator);
	root.PushBack(contact2, allocator);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	root.Accept(writer);
	string reststring = buffer.GetString();
	cout << reststring << endl;
	return 0;
}


输出:

 

注意json输出的字符串双引号还带一个斜杠。

 

Lu//a"
[["Lu//a\"","Mio",""],["Lu// a","Mio",""]]

 

例子2: 对象json.

 

 

void TestJson2()
{
	Document document;
	Document::AllocatorType& allocator = document.GetAllocator();
	Value root(kObjectType);

	Value storage_photo_count(kStringType);
	std::string storage_photo_count_str("49");
	storage_photo_count.SetString(storage_photo_count_str.c_str(),
		storage_photo_count_str.size(),allocator);

	Value storage_music_count(kStringType);
	std::string storage_music_count_str("48");
	storage_music_count.SetString(storage_music_count_str.c_str(),
		storage_music_count_str.size(),allocator);

	root.AddMember("storage.photo.count",storage_photo_count,allocator);
	root.AddMember("storage.music.count",storage_music_count,allocator);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	root.Accept(writer);
	std::string result = buffer.GetString();
	cout << "result: " << result << "..........:" << result.size()<< endl;
}


输出:

 

 

result: {"storage.photo.count":"49","storage.music.count":"48"}..........:55

 

解析Json:

 

 

if (document.Parse<0>(result.c_str()).HasParseError())
	{
		cout << "error" << endl;
	}

	assert(document.HasMember("storage.music.count"));
	cout << document["storage.music.count"].GetString() << endl;


输出:

 

 

48

 

枚举Object

 

 

Document::MemberIterator ite = document.MemberBegin();
	for(; ite != document.MemberEnd(); ++ite)
	{
		const char* name = ite->name.GetString();
		const char* value = ite->value.GetString();
		cout << name << ":" << value << endl;
	}


输出:

 

 

storage.photo.count:49
storage.music.count:48

 

 

 

 

 

 

 

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页
实付 9.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值