summaryrefslogtreecommitdiff
path: root/sl4n/rapidjson/example
diff options
context:
space:
mode:
Diffstat (limited to 'sl4n/rapidjson/example')
-rw-r--r--sl4n/rapidjson/example/capitalize/capitalize.cpp66
-rw-r--r--sl4n/rapidjson/example/condense/condense.cpp32
-rw-r--r--sl4n/rapidjson/example/messagereader/messagereader.cpp96
-rw-r--r--sl4n/rapidjson/example/pretty/pretty.cpp30
-rw-r--r--sl4n/rapidjson/example/prettyauto/prettyauto.cpp56
-rw-r--r--sl4n/rapidjson/example/serialize/serialize.cpp157
-rw-r--r--sl4n/rapidjson/example/simpledom/simpledom.cpp29
-rw-r--r--sl4n/rapidjson/example/simplereader/simplereader.cpp38
-rw-r--r--sl4n/rapidjson/example/simplewriter/simplewriter.cpp35
-rw-r--r--sl4n/rapidjson/example/tutorial/tutorial.cpp151
10 files changed, 0 insertions, 690 deletions
diff --git a/sl4n/rapidjson/example/capitalize/capitalize.cpp b/sl4n/rapidjson/example/capitalize/capitalize.cpp
deleted file mode 100644
index a19ed50..0000000
--- a/sl4n/rapidjson/example/capitalize/capitalize.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-// JSON condenser example
-
-// This example parses JSON from stdin with validation,
-// and re-output the JSON content to stdout with all string capitalized, and without whitespace.
-
-#include "rapidjson/reader.h"
-#include "rapidjson/writer.h"
-#include "rapidjson/filereadstream.h"
-#include "rapidjson/filewritestream.h"
-#include "rapidjson/error/en.h"
-#include <vector>
-#include <cctype>
-
-using namespace rapidjson;
-
-template<typename OutputHandler>
-struct CapitalizeFilter {
- CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
-
- bool Null() { return out_.Null(); }
- bool Bool(bool b) { return out_.Bool(b); }
- bool Int(int i) { return out_.Int(i); }
- bool Uint(unsigned u) { return out_.Uint(u); }
- bool Int64(int64_t i) { return out_.Int64(i); }
- bool Uint64(uint64_t u) { return out_.Uint64(u); }
- bool Double(double d) { return out_.Double(d); }
- bool String(const char* str, SizeType length, bool) {
- buffer_.clear();
- for (SizeType i = 0; i < length; i++)
- buffer_.push_back(std::toupper(str[i]));
- return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
- }
- bool StartObject() { return out_.StartObject(); }
- bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
- bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
- bool StartArray() { return out_.StartArray(); }
- bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
-
- OutputHandler& out_;
- std::vector<char> buffer_;
-
-private:
- CapitalizeFilter(const CapitalizeFilter&);
- CapitalizeFilter& operator=(const CapitalizeFilter&);
-};
-
-int main(int, char*[]) {
- // Prepare JSON reader and input stream.
- Reader reader;
- char readBuffer[65536];
- FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
-
- // Prepare JSON writer and output stream.
- char writeBuffer[65536];
- FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
- Writer<FileWriteStream> writer(os);
-
- // JSON reader parse from the input stream and let writer generate the output.
- CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
- if (!reader.Parse(is, filter)) {
- fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
- return 1;
- }
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/condense/condense.cpp b/sl4n/rapidjson/example/condense/condense.cpp
deleted file mode 100644
index d77f2c7..0000000
--- a/sl4n/rapidjson/example/condense/condense.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// JSON condenser example
-
-// This example parses JSON text from stdin with validation,
-// and re-output the JSON content to stdout without whitespace.
-
-#include "rapidjson/reader.h"
-#include "rapidjson/writer.h"
-#include "rapidjson/filereadstream.h"
-#include "rapidjson/filewritestream.h"
-#include "rapidjson/error/en.h"
-
-using namespace rapidjson;
-
-int main(int, char*[]) {
- // Prepare JSON reader and input stream.
- Reader reader;
- char readBuffer[65536];
- FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
-
- // Prepare JSON writer and output stream.
- char writeBuffer[65536];
- FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
- Writer<FileWriteStream> writer(os);
-
- // JSON reader parse from the input stream and let writer generate the output.
- if (!reader.Parse(is, writer)) {
- fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
- return 1;
- }
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/messagereader/messagereader.cpp b/sl4n/rapidjson/example/messagereader/messagereader.cpp
deleted file mode 100644
index 50255b3..0000000
--- a/sl4n/rapidjson/example/messagereader/messagereader.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-// Reading a message JSON with Reader (SAX-style API).
-// The JSON should be an object with key-string pairs.
-
-#include "rapidjson/reader.h"
-#include "rapidjson/error/en.h"
-#include <iostream>
-#include <string>
-#include <map>
-
-using namespace std;
-using namespace rapidjson;
-
-typedef map<string, string> MessageMap;
-
-#if defined(__GNUC__)
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-struct MessageHandler
- : public BaseReaderHandler<UTF8<>, MessageHandler> {
- MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {}
-
- bool StartObject() {
- switch (state_) {
- case kExpectObjectStart:
- state_ = kExpectNameOrObjectEnd;
- return true;
- default:
- return false;
- }
- }
-
- bool String(const char* str, SizeType length, bool) {
- switch (state_) {
- case kExpectNameOrObjectEnd:
- name_ = string(str, length);
- state_ = kExpectValue;
- return true;
- case kExpectValue:
- messages_.insert(MessageMap::value_type(name_, string(str, length)));
- state_ = kExpectNameOrObjectEnd;
- return true;
- default:
- return false;
- }
- }
-
- bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; }
-
- bool Default() { return false; } // All other events are invalid.
-
- MessageMap messages_;
- enum State {
- kExpectObjectStart,
- kExpectNameOrObjectEnd,
- kExpectValue
- }state_;
- std::string name_;
-};
-
-#if defined(__GNUC__)
-RAPIDJSON_DIAG_POP
-#endif
-
-void ParseMessages(const char* json, MessageMap& messages) {
- Reader reader;
- MessageHandler handler;
- StringStream ss(json);
- if (reader.Parse(ss, handler))
- messages.swap(handler.messages_); // Only change it if success.
- else {
- ParseErrorCode e = reader.GetParseErrorCode();
- size_t o = reader.GetErrorOffset();
- cout << "Error: " << GetParseError_En(e) << endl;;
- cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl;
- }
-}
-
-int main() {
- MessageMap messages;
-
- const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }";
- cout << json1 << endl;
- ParseMessages(json1, messages);
-
- for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr)
- cout << itr->first << ": " << itr->second << endl;
-
- cout << endl << "Parse a JSON with invalid schema." << endl;
- const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }";
- cout << json2 << endl;
- ParseMessages(json2, messages);
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/pretty/pretty.cpp b/sl4n/rapidjson/example/pretty/pretty.cpp
deleted file mode 100644
index 164e388..0000000
--- a/sl4n/rapidjson/example/pretty/pretty.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// JSON pretty formatting example
-// This example can only handle UTF-8. For handling other encodings, see prettyauto example.
-
-#include "rapidjson/reader.h"
-#include "rapidjson/prettywriter.h"
-#include "rapidjson/filereadstream.h"
-#include "rapidjson/filewritestream.h"
-#include "rapidjson/error/en.h"
-
-using namespace rapidjson;
-
-int main(int, char*[]) {
- // Prepare reader and input stream.
- Reader reader;
- char readBuffer[65536];
- FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
-
- // Prepare writer and output stream.
- char writeBuffer[65536];
- FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
- PrettyWriter<FileWriteStream> writer(os);
-
- // JSON reader parse from the input stream and let writer generate the output.
- if (!reader.Parse<kParseValidateEncodingFlag>(is, writer)) {
- fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
- return 1;
- }
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/prettyauto/prettyauto.cpp b/sl4n/rapidjson/example/prettyauto/prettyauto.cpp
deleted file mode 100644
index 0d30968..0000000
--- a/sl4n/rapidjson/example/prettyauto/prettyauto.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-// JSON pretty formatting example
-// This example can handle UTF-8/UTF-16LE/UTF-16BE/UTF-32LE/UTF-32BE.
-// The input firstly convert to UTF8, and then write to the original encoding with pretty formatting.
-
-#include "rapidjson/reader.h"
-#include "rapidjson/prettywriter.h"
-#include "rapidjson/filereadstream.h"
-#include "rapidjson/filewritestream.h"
-#include "rapidjson/encodedstream.h" // NEW
-#include "rapidjson/error/en.h"
-#ifdef _WIN32
-#include <fcntl.h>
-#include <io.h>
-#endif
-
-using namespace rapidjson;
-
-int main(int, char*[]) {
-#ifdef _WIN32
- // Prevent Windows converting between CR+LF and LF
- _setmode(_fileno(stdin), _O_BINARY); // NEW
- _setmode(_fileno(stdout), _O_BINARY); // NEW
-#endif
-
- // Prepare reader and input stream.
- //Reader reader;
- GenericReader<AutoUTF<unsigned>, UTF8<> > reader; // CHANGED
- char readBuffer[65536];
- FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
- AutoUTFInputStream<unsigned, FileReadStream> eis(is); // NEW
-
- // Prepare writer and output stream.
- char writeBuffer[65536];
- FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
-
-#if 1
- // Use the same Encoding of the input. Also use BOM according to input.
- typedef AutoUTFOutputStream<unsigned, FileWriteStream> OutputStream; // NEW
- OutputStream eos(os, eis.GetType(), eis.HasBOM()); // NEW
- PrettyWriter<OutputStream, UTF8<>, AutoUTF<unsigned> > writer(eos); // CHANGED
-#else
- // You may also use static bound encoding type, such as output to UTF-16LE with BOM
- typedef EncodedOutputStream<UTF16LE<>,FileWriteStream> OutputStream; // NEW
- OutputStream eos(os, true); // NEW
- PrettyWriter<OutputStream, UTF8<>, UTF16LE<> > writer(eos); // CHANGED
-#endif
-
- // JSON reader parse from the input stream and let writer generate the output.
- //if (!reader.Parse<kParseValidateEncodingFlag>(is, writer)) {
- if (!reader.Parse<kParseValidateEncodingFlag>(eis, writer)) { // CHANGED
- fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
- return 1;
- }
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/serialize/serialize.cpp b/sl4n/rapidjson/example/serialize/serialize.cpp
deleted file mode 100644
index 7427939..0000000
--- a/sl4n/rapidjson/example/serialize/serialize.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-// Serialize example
-// This example shows writing JSON string with writer directly.
-
-#include "rapidjson/prettywriter.h" // for stringify JSON
-#include <cstdio>
-#include <string>
-#include <vector>
-
-using namespace rapidjson;
-
-class Person {
-public:
- Person(const std::string& name, unsigned age) : name_(name), age_(age) {}
- virtual ~Person();
-
-protected:
- template <typename Writer>
- void Serialize(Writer& writer) const {
- // This base class just write out name-value pairs, without wrapping within an object.
- writer.String("name");
-#ifdef RAPIDJSON_HAS_STDSTRING
- writer.String(name_);
-#else
- writer.String(name_.c_str(), (SizeType)name_.length()); // Supplying length of string is faster.
-#endif
- writer.String("age");
- writer.Uint(age_);
- }
-
-private:
- std::string name_;
- unsigned age_;
-};
-
-Person::~Person() {
-}
-
-class Education {
-public:
- Education(const std::string& school, double GPA) : school_(school), GPA_(GPA) {}
-
- template <typename Writer>
- void Serialize(Writer& writer) const {
- writer.StartObject();
-
- writer.String("school");
-#ifdef RAPIDJSON_HAS_STDSTRING
- writer.String(school_);
-#else
- writer.String(school_.c_str(), (SizeType)school_.length());
-#endif
-
- writer.String("GPA");
- writer.Double(GPA_);
-
- writer.EndObject();
- }
-
-private:
- std::string school_;
- double GPA_;
-};
-
-class Dependent : public Person {
-public:
- Dependent(const std::string& name, unsigned age, Education* education = 0) : Person(name, age), education_(education) {}
- Dependent(const Dependent& rhs) : Person(rhs), education_(0) { education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); }
- virtual ~Dependent();
-
- Dependent& operator=(const Dependent& rhs) {
- if (this == &rhs)
- return *this;
- delete education_;
- education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_);
- return *this;
- }
-
- template <typename Writer>
- void Serialize(Writer& writer) const {
- writer.StartObject();
-
- Person::Serialize(writer);
-
- writer.String("education");
- if (education_)
- education_->Serialize(writer);
- else
- writer.Null();
-
- writer.EndObject();
- }
-
-private:
-
- Education *education_;
-};
-
-Dependent::~Dependent() {
- delete education_;
-}
-
-class Employee : public Person {
-public:
- Employee(const std::string& name, unsigned age, bool married) : Person(name, age), dependents_(), married_(married) {}
- virtual ~Employee();
-
- void AddDependent(const Dependent& dependent) {
- dependents_.push_back(dependent);
- }
-
- template <typename Writer>
- void Serialize(Writer& writer) const {
- writer.StartObject();
-
- Person::Serialize(writer);
-
- writer.String("married");
- writer.Bool(married_);
-
- writer.String(("dependents"));
- writer.StartArray();
- for (std::vector<Dependent>::const_iterator dependentItr = dependents_.begin(); dependentItr != dependents_.end(); ++dependentItr)
- dependentItr->Serialize(writer);
- writer.EndArray();
-
- writer.EndObject();
- }
-
-private:
- std::vector<Dependent> dependents_;
- bool married_;
-};
-
-Employee::~Employee() {
-}
-
-int main(int, char*[]) {
- std::vector<Employee> employees;
-
- employees.push_back(Employee("Milo YIP", 34, true));
- employees.back().AddDependent(Dependent("Lua YIP", 3, new Education("Happy Kindergarten", 3.5)));
- employees.back().AddDependent(Dependent("Mio YIP", 1));
-
- employees.push_back(Employee("Percy TSE", 30, false));
-
- StringBuffer sb;
- PrettyWriter<StringBuffer> writer(sb);
-
- writer.StartArray();
- for (std::vector<Employee>::const_iterator employeeItr = employees.begin(); employeeItr != employees.end(); ++employeeItr)
- employeeItr->Serialize(writer);
- writer.EndArray();
-
- puts(sb.GetString());
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/simpledom/simpledom.cpp b/sl4n/rapidjson/example/simpledom/simpledom.cpp
deleted file mode 100644
index 8038419..0000000
--- a/sl4n/rapidjson/example/simpledom/simpledom.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-// JSON simple example
-// This example does not handle errors.
-
-#include "rapidjson/document.h"
-#include "rapidjson/writer.h"
-#include "rapidjson/stringbuffer.h"
-#include <iostream>
-
-using namespace rapidjson;
-
-int main() {
- // 1. Parse a JSON string into DOM.
- const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
- Document d;
- d.Parse(json);
-
- // 2. Modify it by DOM.
- Value& s = d["stars"];
- s.SetInt(s.GetInt() + 1);
-
- // 3. Stringify the DOM
- StringBuffer buffer;
- Writer<StringBuffer> writer(buffer);
- d.Accept(writer);
-
- // Output {"project":"rapidjson","stars":11}
- std::cout << buffer.GetString() << std::endl;
- return 0;
-}
diff --git a/sl4n/rapidjson/example/simplereader/simplereader.cpp b/sl4n/rapidjson/example/simplereader/simplereader.cpp
deleted file mode 100644
index edbdb63..0000000
--- a/sl4n/rapidjson/example/simplereader/simplereader.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "rapidjson/reader.h"
-#include <iostream>
-
-using namespace rapidjson;
-using namespace std;
-
-struct MyHandler {
- bool Null() { cout << "Null()" << endl; return true; }
- bool Bool(bool b) { cout << "Bool(" << boolalpha << b << ")" << endl; return true; }
- bool Int(int i) { cout << "Int(" << i << ")" << endl; return true; }
- bool Uint(unsigned u) { cout << "Uint(" << u << ")" << endl; return true; }
- bool Int64(int64_t i) { cout << "Int64(" << i << ")" << endl; return true; }
- bool Uint64(uint64_t u) { cout << "Uint64(" << u << ")" << endl; return true; }
- bool Double(double d) { cout << "Double(" << d << ")" << endl; return true; }
- bool String(const char* str, SizeType length, bool copy) {
- cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl;
- return true;
- }
- bool StartObject() { cout << "StartObject()" << endl; return true; }
- bool Key(const char* str, SizeType length, bool copy) {
- cout << "Key(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl;
- return true;
- }
- bool EndObject(SizeType memberCount) { cout << "EndObject(" << memberCount << ")" << endl; return true; }
- bool StartArray() { cout << "StartArray()" << endl; return true; }
- bool EndArray(SizeType elementCount) { cout << "EndArray(" << elementCount << ")" << endl; return true; }
-};
-
-int main() {
- const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
-
- MyHandler handler;
- Reader reader;
- StringStream ss(json);
- reader.Parse(ss, handler);
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/simplewriter/simplewriter.cpp b/sl4n/rapidjson/example/simplewriter/simplewriter.cpp
deleted file mode 100644
index f889150..0000000
--- a/sl4n/rapidjson/example/simplewriter/simplewriter.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "rapidjson/writer.h"
-#include "rapidjson/stringbuffer.h"
-#include <iostream>
-
-using namespace rapidjson;
-using namespace std;
-
-int main() {
- StringBuffer s;
- Writer<StringBuffer> writer(s);
-
- writer.StartObject();
- writer.String("hello");
- writer.String("world");
- writer.String("t");
- writer.Bool(true);
- writer.String("f");
- writer.Bool(false);
- writer.String("n");
- writer.Null();
- writer.String("i");
- writer.Uint(123);
- writer.String("pi");
- writer.Double(3.1416);
- writer.String("a");
- writer.StartArray();
- for (unsigned i = 0; i < 4; i++)
- writer.Uint(i);
- writer.EndArray();
- writer.EndObject();
-
- cout << s.GetString() << endl;
-
- return 0;
-}
diff --git a/sl4n/rapidjson/example/tutorial/tutorial.cpp b/sl4n/rapidjson/example/tutorial/tutorial.cpp
deleted file mode 100644
index 206fdb9..0000000
--- a/sl4n/rapidjson/example/tutorial/tutorial.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-// 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 1;
-#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 1;
-#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()) == 0);
- (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 = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
- printf("a[%d] = %d\n", i, a[i].GetInt());
-
- int y = a[0].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 = 1; // compute factorial of 20
- for (uint64_t j = 1; j <= 20; 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 = 5; i <= 10; 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 buffer[10];
- int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string.
-
- author.SetString(buffer, static_cast<size_t>(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(buffer, 0, sizeof(buffer)); // 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 0;
-}