生成数组集合的字符串

#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 使用的更多相关文章

  1. RapidJSON v1.1.0 发布简介

    时隔 15.6 个月,终于发布了一个新版本 v1.1.0. 新版本除了包含了这些日子收集到的无数的小改进及 bug fixes,也有一些新功能.本文尝试从使用者的角度,简单介绍一下这些功能和沿由. P ...

  2. RapidJSON 代码剖析(四):优化 Grisu

    我曾经在知乎的一个答案里谈及到 V8 引擎里实现了 Grisu 算法,我先引用该文的内容简单介绍 Grisu.然后,再谈及 RapidJSON 对它做了的几个底层优化. (配图中的<Grisù& ...

  3. RapidJSON 代码剖析(三):Unicode 的编码与解码

    根据 RFC-7159: 8.1 Character Encoding JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32. The defa ...

  4. RapidJSON 代码剖析(二):使用 SSE4.2 优化字符串扫描

    现在的 CPU 都提供了单指令流多数据流(single instruction multiple data, SIMD)指令集.最常见的是用于大量的浮点数计算,但其实也可以用在文字处理方面. 其中,S ...

  5. RapidJSON 代码剖析(一):混合任意类型的堆栈

    大家好,这个专栏会分析 RapidJSON (中文使用手册)中一些有趣的 C++ 代码,希望对读者有所裨益. C++ 语法解说 我们先来看一行代码(document.h): bool StartArr ...

  6. RapidJson读取json文档

    Json格式定义如下 Object: { _Name:_Data,... } 最后一项后面没有逗号 Array: [_Data,_Data,...] 最后一项后面没有逗号 _Name: String ...

  7. 这个东西,写C++插件的可以用到。 RapidJSON —— C++ 快速 JSON 解析器和生成器

    点这里 原文: RapidJSON —— C++ 快速 JSON 解析器和生成器 时间 2015-04-05 07:33:33  开源中国新闻原文  http://www.oschina.net/p/ ...

  8. Cocos2d-x移植到WindowsPhone8移植问题-框架rapidjson移植问题

    Cocos2d-x 3.0提供了JSON框架rapidjson可以在Windows Phone 8平台使用,如果没有进行必要的配置,在编译的时候会报错,document.h等头文件找不到的错误.在Wi ...

  9. cocos2d-x3.x使用rapidjson

    rapidjson效率高,所以之前cocostudio里面解析用的jsoncpp也换成了rapidjson. 引擎又带有rapidjson库,所以不用单独去下载,直接就可以用. 这里主要写一下关于解析 ...

  10. cocos2dx 3.2 定义自己使用rapidjson阅读json数据

    一.说明 我在这里得到的只是一个简单的定义string和Int种类,其他数据类型可以被替换向上. 两.头文件 class JsonReadUtils { public: static JsonRead ...

随机推荐

  1. T-SQL Part V: Locks

    写SQL最常见的问题就是Dead Lock了.本篇简单介绍入门级别的Lock使用和排查. 首先来看MSDN上的官方文档(https://technet.microsoft.com/en-us/libr ...

  2. 【前端知识体系-CSS相关】Bootstrap相关知识

    1.Bootstrap 的优缺点? 优点:CSS代码结构合理,现成的代码可以直接使用(响应式布局) 缺点:定制流程较为繁琐,体积大 2.如何实现响应式布局? 原理:通过media query设置不同分 ...

  3. django_4:数据库0——配置数据库

    使用Mysql数据库 (python需要能连接上mysql,见别的文档:python3+django 支持 mysql) 启动mysql服务 修改setting.py同目录 下的__init__.py ...

  4. objc反汇编分析,block函数块为何物?

    上一篇向大家介绍了__block变量的反汇编和它的伪代码,本篇函数块block,通常定义成原型(^){},它在反汇编中是什么东西. 我们先定义将要反汇编的例子,为减少篇幅例子采用non-arc环境. ...

  5. java.lang.NoSuchMethodError: org.apache.tomcat.JarScanner.scan(Ljavax/servlet/ServletContext;Ljava/lang/ClassLoader;Lorg/apache/tomcat/JarScannerCallback;Ljava/util/Set;)V

    java.lang.NoSuchMethodError: org.apache.tomcat.JarScanner.scan(Ljavax/servlet/ServletContext;Ljava/l ...

  6. Cygwin安装教程

    cygwin是一个在windows平台上运行的unix模拟环境,是cygnus solutions公司开发的自由软件. 它对于学习unix/linux操作环境,或者从unix到windows的应用程序 ...

  7. http_web_cache

    HTTP Web Cache 程序资源的访问具有局部性 时间局部性:一个被访问过的资源很有可能在近期被再次访问. 空间局部性:一个被访问过的资源,它的周边资源很有可能被访问到. 如何衡量缓存的有效性? ...

  8. Mybatis日志体系

    承接上一篇关于spring 5.x的日志体系,本篇看看Mybatis的日志体系及实现,Mybatis版本基于3.x. 关于mybatis的官方文档比较友好,分门别类,各有论述,如mybatis官方文档 ...

  9. ctf中关于图片的隐写随笔(不全)

    ①JPG图片的结束符,十六进制常为FFD9 ②binwalk的原理是:检查常见的文件头信息,如果不符合,一定有隐藏信息.③JPG是有损压缩,PNG是无损压缩,BMP是不压缩. 隐写的基本原理:图片查看 ...

  10. windows和linux的开机顺序

    windows的开机顺序: 启动自检阶段---初始化启动阶段---Boot加载阶段---检测和配置硬件阶段---内核加载阶段---屏幕显示. linux的开机启动顺序: 加载Bios---读取MBR- ...