生成数组集合的字符串

#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. ACGallery I: Sequence diagram for reading photos:

    AC Photo Gallery is an open-source web app, which designed to organize photos/albums. Codes on Githu ...

  2. thinkphp5配合datatable插件分页后端处理程序

    thinkphp5配合datatable插件分页后端处理程序第一版DataTable.php v.1.0 <?php use think\Db; /** * DataTable.php. */ ...

  3. [java] 计算时间复杂度

    一.精算: 1.所有的声明,都不计时间: 2.赋值语句占1个时间单位(下称:单位),比如sum=0: 3.return占1个单位,比如,reeturn sum.     我怀疑范围一个链表头,不止占1 ...

  4. Java编程思想——第14章 类型信息(二)反射

    六.反射:运行时的类信息 我们已经知道了,在编译时,编译器必须知道所有要通过RTTI来处理的类.而反射提供了一种机制——用来检查可用的方法,并返回方法名.区别就在于RTTI是处理已知类的,而反射用于处 ...

  5. java中hashmap容量的初始化

    HashMap使用HashMap(int initialCapacity)对集合进行初始化. 在默认的情况下,HashMap的容量是16.但是如果用户通过构造函数指定了一个数字作为容量,那么Hash会 ...

  6. 关键路径法(Critical Path Method, CPM)

    1.活动节点描述及计算公式 通过分析项目过程中哪个活动序列进度安排的总时差最少来预测项目工期的网络分析. 产生目的:为了解决,在庞大而复杂的项目中,如何合理而有效地组织人力.物力和财力,使之在有限资源 ...

  7. JS三座大山再学习(一、原型和原型链)

    原文地址 ## 前言 西瓜君之前学习了JS的基础知识与三座大山,但之后工作中没怎么用,印象不太深刻,这次打算再重学一下,打牢基础.冲鸭~~ 原型模式 JS实现继承的方式是通过原型和原型链实现的,JS中 ...

  8. list,tuple,dict,set 思维导图整理

  9. selenium针对浏览器滚动条的操作

    我们在实际自动化测试过程中,肯定会遇到当前页面显示不到我们定位的元素.这就需要下拉滚动条才能显示出我们的元素: 而滚动条的按钮又是我们定位不到的,所以需要使用js脚本来完成: 1.先来说我们的下拉滚动 ...

  10. 记一次Pod中java进程内存“异常”消耗

    背景 环境:openshift3.11 开发反映部署在容器中的java应用内存持续增长,只升不降,具体为: java应用部署在容器中,配置的jvm参数为-Xms1024m -Xmx1024m,容器me ...