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 ...
随机推荐
- python 豆瓣top250电影的爬取
我们先看一下豆瓣的robot.txt 然后我们查看top250的网页链接和源代码 通过对比不难发现网页间只是start数字发生了变化. 我们可以知道电影内容都存在ol标签下的 div class属性为 ...
- Flutter 构建的 Mac 桌面应用上无法发出网络?
在上一篇文章中我们分享了,如何开发桌面应用.在本章文章中,来解决一下为何在 Mac 中无法发出网络情况的原因. 起因 事情起因是这样的:我总觉得写一个 Demo 不足以体现我们开发同学的能力.直到最 ...
- nyoj 50-爱摘苹果的小明 (比较)
50-爱摘苹果的小明 内存限制:64MB 时间限制:1000ms Special Judge: No accepted:10 submit:15 题目描述: 小明家的院子里有一棵苹果树,每到秋天树上就 ...
- 力扣(LeetCode)4的幂 个人题解
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方. 示例 1: 输入: 16 输出: true 示例 2: 输入: 5 输出: false 进阶:你能不使用循环或者递归 ...
- 力扣(LeetCode)删除排序链表中的重复元素 个人题解
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次. 这题思路比较简单,同样是快慢针的思路. 用一个整数类型val对应最新的只出现过一次的那个值, 如果节点的下一个节点的值和这个对应则不做别 ...
- gin索引优化实例1
GIN(Generalized Inverted Index, 通用倒排索引) 是一个存储对(key, posting list)集合的索引结构,其中key是一个键值,而posting list 是一 ...
- vue项目中安装使用vux
vux是个vue的移动端框架. 目前移动端UI框架这么多,为啥选择vux呢?vux虽然说是个个人维护项目,但是有15000+个star,应该不比其他的团队开源框架差. 最重要的是,目前要做微信公众号和 ...
- gulp 自动化构建html项目--自动刷新
使用gulp自动化构建项目是前端学习的重要部分,gulp依赖于node.js.首选电脑要配置node和npm. 查看node版本号 node --version 查看npm 版本 npm --vers ...
- 题解-洛谷P2010-回文日期
原题链接: https://www.luogu.org/problem/P2010 题目简述: 牛牛习惯用8位数字表示一个日期,其中,前4位代表年份,接下来2位代表月份,最后22位代表日期.显然:一个 ...
- .net压缩文件
首先nuget安装DotNetZip 代码很少