rapidjson 使用
生成数组集合的字符串
#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 ;
}
输出:
Lu//a"
[["Lu//a\"","Mio",""],["Lu// a","Mio",""]]
对象json
void TestJson2()
{
Document document;
Document::AllocatorType& allocator = document.GetAllocator();
Value root(kObjectType); Value storage_photo_count(kStringType);
std::string storage_photo_count_str("");
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("");
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;
}
枚举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;
}
/// 添加一个String对象;
rapidjson::Document::AllocatorType&allocator = doc.GetAllocator(); ///< 获取最初数据的分配器
rapidjson::Value strObject(rapidjson::kStringType); ///<添加字符串方法1
strObject.SetString("love");
doc.AddMember("hello1", strObject,allocator);
/* doc.AddMember("hello1","love you", allocator); ///<添加字符串方法2:往分配器中添加一个对象*/ /// 添加一个null对象
rapidjson::Value nullObject(rapidjson::kNullType);
doc.AddMember("null", nullObject,allocator); ///<往分配器中添加一个对象 /// 添加一个数组对象
rapidjson::Value array(rapidjson::kArrayType); ///< 创建一个数组对象
rapidjson::Value object(rapidjson::kObjectType); ///<创建数组里面对象。
object.AddMember("id", 1,allocator);
object.AddMember("name","lai", allocator);
object.AddMember("age", "",allocator);
object.AddMember("low", true,allocator);
array.PushBack(object, allocator);
doc.AddMember("player", array,allocator); ///<将上述的数组内容添加到一个名为“player”的数组中 /// 在已有的数组中添加一个成员对象
rapidjson::Value& aArray1 = doc["a"];
aArray1.PushBack(2.0, allocator);
gitlab上例子
// Hello World example
// This example shows basic usage of DOM-style API. #include "rapidjson/document.h" // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h" // for stringify JSON
#include <cstdio> using namespace rapidjson;
using namespace std; int main(int, char*[]) {
////////////////////////////////////////////////////////////////////////////
// 1. Parse a JSON text string to a document. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
printf("Original JSON:\n %s\n", json); Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. #if 0
// "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream().
if (document.Parse(json).HasParseError())
return ;
#else
// In-situ parsing, decode strings directly in the source string. Source must be string.
char buffer[sizeof(json)];
memcpy(buffer, json, sizeof(json));
if (document.ParseInsitu(buffer).HasParseError())
return ;
#endif printf("\nParsing to document succeeded.\n"); ////////////////////////////////////////////////////////////////////////////
// 2. Access values in document. printf("\nAccess values in document:\n");
assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array. assert(document.HasMember("hello"));
assert(document["hello"].IsString());
printf("hello = %s\n", document["hello"].GetString()); // Since version 0.2, you can use single lookup to check the existing of member and its value:
Value::MemberIterator hello = document.FindMember("hello");
assert(hello != document.MemberEnd());
assert(hello->value.IsString());
assert(strcmp("world", hello->value.GetString()) == );
(void)hello; assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue().
printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); assert(document["f"].IsBool());
printf("f = %s\n", document["f"].GetBool() ? "true" : "false"); printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type.
assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true.
printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"] assert(document["pi"].IsNumber());
assert(document["pi"].IsDouble());
printf("pi = %g\n", document["pi"].GetDouble()); {
const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster.
assert(a.IsArray());
for (SizeType i = ; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
printf("a[%d] = %d\n", i, a[i].GetInt()); int y = a[].GetInt();
(void)y; // Iterating array with iterators
printf("a = ");
for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
printf("%d ", itr->GetInt());
printf("\n");
} // Iterating object members
static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr)
printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]); ////////////////////////////////////////////////////////////////////////////
// 3. Modify values in document. // Change i to a bigger number
{
uint64_t f20 = ; // compute factorial of 20
for (uint64_t j = ; j <= ; j++)
f20 *= j;
document["i"] = f20; // Alternate form: document["i"].SetUint64(f20)
assert(!document["i"].IsInt()); // No longer can be cast as int or uint.
} // Adding values to array.
{
Value& a = document["a"]; // This time we uses non-const reference.
Document::AllocatorType& allocator = document.GetAllocator();
for (int i = ; i <= ; i++)
a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's. // Fluent API
a.PushBack("Lua", allocator).PushBack("Mio", allocator);
} // Making string values. // This version of SetString() just store the pointer to the string.
// So it is for literal and string that exists within value's life-cycle.
{
document["hello"] = "rapidjson"; // This will invoke strlen()
// Faster version:
// document["hello"].SetString("rapidjson", 9);
} // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer.
Value author;
{
char buffer2[];
int len = sprintf(buffer2, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string. author.SetString(buffer2, static_cast<SizeType>(len), document.GetAllocator());
// Shorter but slower version:
// document["hello"].SetString(buffer, document.GetAllocator()); // Constructor version:
// Value author(buffer, len, document.GetAllocator());
// Value author(buffer, document.GetAllocator());
memset(buffer2, , sizeof(buffer2)); // For demonstration purpose.
}
// Variable 'buffer' is unusable now but 'author' has already made a copy.
document.AddMember("author", author, document.GetAllocator()); assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null. ////////////////////////////////////////////////////////////////////////////
// 4. Stringify JSON printf("\nModified JSON with reformatting:\n");
StringBuffer sb;
PrettyWriter<StringBuffer> writer(sb);
document.Accept(writer); // Accept() traverses the DOM and generates Handler events.
puts(sb.GetString()); return ;
}
官网:http://rapidjson.org/zh-cn/
参考:http://blog.csdn.net/infoworld/article/details/9625129
http://www.bkjia.com/Androidjc/884053.html
https://github.com/miloyip/rapidjson/blob/master/example/tutorial/tutorial.cpp
rapidjson 使用的更多相关文章
- RapidJSON v1.1.0 发布简介
时隔 15.6 个月,终于发布了一个新版本 v1.1.0. 新版本除了包含了这些日子收集到的无数的小改进及 bug fixes,也有一些新功能.本文尝试从使用者的角度,简单介绍一下这些功能和沿由. P ...
- RapidJSON 代码剖析(四):优化 Grisu
我曾经在知乎的一个答案里谈及到 V8 引擎里实现了 Grisu 算法,我先引用该文的内容简单介绍 Grisu.然后,再谈及 RapidJSON 对它做了的几个底层优化. (配图中的<Grisù& ...
- RapidJSON 代码剖析(三):Unicode 的编码与解码
根据 RFC-7159: 8.1 Character Encoding JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32. The defa ...
- RapidJSON 代码剖析(二):使用 SSE4.2 优化字符串扫描
现在的 CPU 都提供了单指令流多数据流(single instruction multiple data, SIMD)指令集.最常见的是用于大量的浮点数计算,但其实也可以用在文字处理方面. 其中,S ...
- RapidJSON 代码剖析(一):混合任意类型的堆栈
大家好,这个专栏会分析 RapidJSON (中文使用手册)中一些有趣的 C++ 代码,希望对读者有所裨益. C++ 语法解说 我们先来看一行代码(document.h): bool StartArr ...
- RapidJson读取json文档
Json格式定义如下 Object: { _Name:_Data,... } 最后一项后面没有逗号 Array: [_Data,_Data,...] 最后一项后面没有逗号 _Name: String ...
- 这个东西,写C++插件的可以用到。 RapidJSON —— C++ 快速 JSON 解析器和生成器
点这里 原文: RapidJSON —— C++ 快速 JSON 解析器和生成器 时间 2015-04-05 07:33:33 开源中国新闻原文 http://www.oschina.net/p/ ...
- Cocos2d-x移植到WindowsPhone8移植问题-框架rapidjson移植问题
Cocos2d-x 3.0提供了JSON框架rapidjson可以在Windows Phone 8平台使用,如果没有进行必要的配置,在编译的时候会报错,document.h等头文件找不到的错误.在Wi ...
- cocos2d-x3.x使用rapidjson
rapidjson效率高,所以之前cocostudio里面解析用的jsoncpp也换成了rapidjson. 引擎又带有rapidjson库,所以不用单独去下载,直接就可以用. 这里主要写一下关于解析 ...
- cocos2dx 3.2 定义自己使用rapidjson阅读json数据
一.说明 我在这里得到的只是一个简单的定义string和Int种类,其他数据类型可以被替换向上. 两.头文件 class JsonReadUtils { public: static JsonRead ...
随机推荐
- c#Func委托
public delegate TResult Func<in T, out TResult>(T arg); 参数类型 T:此委托方法的参数类型 TResult:此委托方法的返回值类型 ...
- 4. 彤哥说netty系列之Java NIO实现群聊(自己跟自己聊上瘾了)
你好,我是彤哥,本篇是netty系列的第四篇. 欢迎来我的公从号彤哥读源码系统地学习源码&架构的知识. 简介 上一章我们一起学习了Java中的BIO/NIO/AIO的故事,本章将带着大家一起使 ...
- HTML5之worker开启JS多线程模式及window.postMessage跨域
worker概述 worker基本使用 window下的postMessage worker多线程的应用 一.worker概述 web worker实际上是开启js异步执行的一种方式.在html5之前 ...
- 力扣(LeetCode)整数形式的整数加法 个人题解
对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组.例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]. 给定非负整数 X 的数组形式 A,返回整数 X+K 的 ...
- django_4:数据库0——配置数据库
使用Mysql数据库 (python需要能连接上mysql,见别的文档:python3+django 支持 mysql) 启动mysql服务 修改setting.py同目录 下的__init__.py ...
- django:runserver实现远程访问
如果是在另一台电脑上web访问要用 python manage.py ip:port (一般使用8000)的形式:监听所有ip用0.0.0.0如下: 1 2 3 python manage.py ru ...
- F#周报2019年第47期
新闻 相遇WebWindow,.NET Core上的跨平台webview类库 使用Bolero在WebAssembly中运行F# 用于你团队代码库的AI辅助IntelliSense Jupyter N ...
- 解决无法定位软件包 或 install net-tools
解决无法定位软件包 或 install net-tools 当我们安装好Linux后,因为里面有很多功能服务没有安装(如ifconfig.vsftpd) 所以出现一些command '**** ...
- Spring中的事务回滚机制
初学者笔记 问题:在Java项目汇中,添加@Transactional注解,报错之后,事务回滚未生效,数据仍插入数据库中.经查看报错位置位于新增成功之后.空指针异常. 一.特性 先了解一下@Trans ...
- Golang 指针理解
目录 0x00 指针地址和指针类型 0x01 从指针获取指针指向的值 0x02 使用指针修改值 0x03 返回函数中局部变量 0x04 使用 new() 创建指针 0x05 flag包的指针技术 0x ...