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

前端之家收集整理的这篇文章主要介绍了[rapidjson]_[C/C++]_[rapidjson库使用简单介绍]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


场景:

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

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

3.官网: http://code.google.com/p/rapidjson/wiki/UserGuide#4._Document

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);
	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",""]]

例子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
原文链接:https://www.f2er.com/json/290418.html

猜你在找的Json相关文章