diff options
author | Milo Yip <miloyip@gmail.com> | 2014-08-11 18:26:45 +0400 |
---|---|---|
committer | Milo Yip <miloyip@gmail.com> | 2014-08-11 18:26:45 +0400 |
commit | 0dbcc1cf2ea62a40adf2f713bdb21685d85653ed (patch) | |
tree | 1165cb491d656e5d5220da184ff432bacb50d3fa /example | |
parent | adb3974e4d078e253a31f4e9e034583bf41298d8 (diff) |
Add license and change indents from tab to space.
Diffstat (limited to 'example')
-rw-r--r-- | example/capitalize/capitalize.cpp | 74 | ||||
-rw-r--r-- | example/condense/condense.cpp | 28 | ||||
-rw-r--r-- | example/messagereader/messagereader.cpp | 70 | ||||
-rw-r--r-- | example/pretty/pretty.cpp | 28 | ||||
-rw-r--r-- | example/prettyauto/prettyauto.cpp | 56 | ||||
-rw-r--r-- | example/serialize/serialize.cpp | 162 | ||||
-rw-r--r-- | example/simpledom/simpledom.cpp | 28 | ||||
-rw-r--r-- | example/simplereader/simplereader.cpp | 32 | ||||
-rw-r--r-- | example/simplewriter/simplewriter.cpp | 2 | ||||
-rw-r--r-- | example/tutorial/tutorial.cpp | 280 |
10 files changed, 380 insertions, 380 deletions
diff --git a/example/capitalize/capitalize.cpp b/example/capitalize/capitalize.cpp index 69b07d8f..b8d60860 100644 --- a/example/capitalize/capitalize.cpp +++ b/example/capitalize/capitalize.cpp @@ -15,51 +15,51 @@ using namespace rapidjson; template<typename OutputHandler> struct CapitalizeFilter { - CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {} + 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 EndObject(SizeType memberCount) { return out_.EndObject(memberCount); } - bool StartArray() { return out_.StartArray(); } - bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); } + 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 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_; + OutputHandler& out_; + std::vector<char> buffer_; private: - CapitalizeFilter(const CapitalizeFilter&); - CapitalizeFilter& operator=(const CapitalizeFilter&); + 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 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); + // 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; - } + // 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; + return 0; } diff --git a/example/condense/condense.cpp b/example/condense/condense.cpp index bad3c91f..05e2007c 100644 --- a/example/condense/condense.cpp +++ b/example/condense/condense.cpp @@ -12,21 +12,21 @@ 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 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);
+ // 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;
- }
+ // 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;
+ return 0;
}
diff --git a/example/messagereader/messagereader.cpp b/example/messagereader/messagereader.cpp index f5317c22..cf6f1e12 100644 --- a/example/messagereader/messagereader.cpp +++ b/example/messagereader/messagereader.cpp @@ -18,38 +18,38 @@ RAPIDJSON_DIAG_OFF(effc++) #endif struct MessageHandler : public BaseReaderHandler<> { - MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {} + MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {} bool StartObject() { - switch (state_) { - case kExpectObjectStart: - state_ = kExpectNameOrObjectEnd; - return true; - default: - return false; - } + switch (state_) { + case kExpectObjectStart: + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } } bool String(const char* str, SizeType length, bool) { - switch (state_) { - case kExpectNameOrObjectEnd: + 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; - } + 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. + bool Default() { return false; } // All other events are invalid. - MessageMap messages_; + MessageMap messages_; enum State { kExpectObjectStart, kExpectNameOrObjectEnd, @@ -66,30 +66,30 @@ 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; - } + 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; + 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); + 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/example/pretty/pretty.cpp b/example/pretty/pretty.cpp index cfb3f0fd..164e3880 100644 --- a/example/pretty/pretty.cpp +++ b/example/pretty/pretty.cpp @@ -10,21 +10,21 @@ using namespace rapidjson;
int main(int, char*[]) {
- // Prepare reader and input stream.
- Reader reader;
- char readBuffer[65536];
- FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
+ // 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);
+ // 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;
- }
+ // 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;
+ return 0;
}
diff --git a/example/prettyauto/prettyauto.cpp b/example/prettyauto/prettyauto.cpp index 3f85f405..0d309686 100644 --- a/example/prettyauto/prettyauto.cpp +++ b/example/prettyauto/prettyauto.cpp @@ -6,7 +6,7 @@ #include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
-#include "rapidjson/encodedstream.h" // NEW
+#include "rapidjson/encodedstream.h" // NEW
#include "rapidjson/error/en.h"
#ifdef _WIN32
#include <fcntl.h>
@@ -17,40 +17,40 @@ 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
+ // 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 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));
+ // 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
+ // 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
+ // 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;
- }
+ // 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;
+ return 0;
}
diff --git a/example/serialize/serialize.cpp b/example/serialize/serialize.cpp index 6dfe2d48..68a54efc 100644 --- a/example/serialize/serialize.cpp +++ b/example/serialize/serialize.cpp @@ -1,8 +1,8 @@ // Serialize example
// This example shows writing JSON string with writer directly.
-#include "rapidjson/prettywriter.h" // for stringify JSON
-#include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output
+#include "rapidjson/prettywriter.h" // for stringify JSON
+#include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output
#include <cstdio>
#include <string>
#include <vector>
@@ -11,23 +11,23 @@ using namespace rapidjson; class Person {
public:
- Person(const std::string& name, unsigned age) : name_(name), age_(age) {}
- virtual ~Person();
+ 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");
- writer.String(name_.c_str(), (SizeType)name_.length()); // Suppling length of string is faster.
+ 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");
+ writer.String(name_.c_str(), (SizeType)name_.length()); // Suppling length of string is faster.
- writer.String("age");
- writer.Uint(age_);
- }
+ writer.String("age");
+ writer.Uint(age_);
+ }
private:
- std::string name_;
- unsigned age_;
+ std::string name_;
+ unsigned age_;
};
Person::~Person() {
@@ -35,115 +35,115 @@ Person::~Person() { class Education {
public:
- Education(const std::string& school, double GPA) : school_(school), GPA_(GPA) {}
+ Education(const std::string& school, double GPA) : school_(school), GPA_(GPA) {}
- template <typename Writer>
- void Serialize(Writer& writer) const {
- writer.StartObject();
-
- writer.String("school");
- writer.String(school_.c_str(), (SizeType)school_.length());
+ template <typename Writer>
+ void Serialize(Writer& writer) const {
+ writer.StartObject();
+
+ writer.String("school");
+ writer.String(school_.c_str(), (SizeType)school_.length());
- writer.String("GPA");
- writer.Double(GPA_);
+ writer.String("GPA");
+ writer.Double(GPA_);
- writer.EndObject();
- }
+ writer.EndObject();
+ }
private:
- std::string school_;
- double GPA_;
+ 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(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;
+ Dependent& operator=(const Dependent& rhs) {
+ if (this == &rhs)
+ return *this;
delete education_;
- education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_);
- return *this;
- }
+ education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_);
+ return *this;
+ }
- template <typename Writer>
- void Serialize(Writer& writer) const {
- writer.StartObject();
+ template <typename Writer>
+ void Serialize(Writer& writer) const {
+ writer.StartObject();
- Person::Serialize(writer);
+ Person::Serialize(writer);
- writer.String("education");
- if (education_)
- education_->Serialize(writer);
- else
- writer.Null();
+ writer.String("education");
+ if (education_)
+ education_->Serialize(writer);
+ else
+ writer.Null();
- writer.EndObject();
- }
+ writer.EndObject();
+ }
private:
- Education *education_;
+ Education *education_;
};
Dependent::~Dependent() {
- delete education_;
+ delete education_;
}
class Employee : public Person {
public:
- Employee(const std::string& name, unsigned age, bool married) : Person(name, age), dependents_(), married_(married) {}
- virtual ~Employee();
+ 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);
- }
+ void AddDependent(const Dependent& dependent) {
+ dependents_.push_back(dependent);
+ }
- template <typename Writer>
- void Serialize(Writer& writer) const {
- writer.StartObject();
+ template <typename Writer>
+ void Serialize(Writer& writer) const {
+ writer.StartObject();
- Person::Serialize(writer);
+ Person::Serialize(writer);
- writer.String("married");
- writer.Bool(married_);
+ 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.String(("dependents"));
+ writer.StartArray();
+ for (std::vector<Dependent>::const_iterator dependentItr = dependents_.begin(); dependentItr != dependents_.end(); ++dependentItr)
+ dependentItr->Serialize(writer);
+ writer.EndArray();
- writer.EndObject();
- }
+ writer.EndObject();
+ }
private:
- std::vector<Dependent> dependents_;
- bool married_;
+ std::vector<Dependent> dependents_;
+ bool married_;
};
Employee::~Employee() {
}
int main(int, char*[]) {
- std::vector<Employee> employees;
+ 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("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));
+ employees.push_back(Employee("Percy TSE", 30, false));
- FileStream s(stdout);
- PrettyWriter<FileStream> writer(s); // Can also use Writer for condensed formatting
+ FileStream s(stdout);
+ PrettyWriter<FileStream> writer(s); // Can also use Writer for condensed formatting
- writer.StartArray();
- for (std::vector<Employee>::const_iterator employeeItr = employees.begin(); employeeItr != employees.end(); ++employeeItr)
- employeeItr->Serialize(writer);
- writer.EndArray();
+ writer.StartArray();
+ for (std::vector<Employee>::const_iterator employeeItr = employees.begin(); employeeItr != employees.end(); ++employeeItr)
+ employeeItr->Serialize(writer);
+ writer.EndArray();
- return 0;
+ return 0;
}
diff --git a/example/simpledom/simpledom.cpp b/example/simpledom/simpledom.cpp index a2c9121f..80384199 100644 --- a/example/simpledom/simpledom.cpp +++ b/example/simpledom/simpledom.cpp @@ -9,21 +9,21 @@ using namespace rapidjson; int main() { - // 1. Parse a JSON string into DOM. - const char* json = "{\"project\":\"rapidjson\",\"stars\":10}"; - Document d; - d.Parse(json); + // 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); + // 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); + // 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; + // Output {"project":"rapidjson","stars":11} + std::cout << buffer.GetString() << std::endl; + return 0; } diff --git a/example/simplereader/simplereader.cpp b/example/simplereader/simplereader.cpp index ed2bd3bf..9914253d 100644 --- a/example/simplereader/simplereader.cpp +++ b/example/simplereader/simplereader.cpp @@ -5,21 +5,21 @@ 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 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 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; } + cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool StartObject() { cout << "StartObject()" << 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() { @@ -28,7 +28,7 @@ int main() { MyHandler handler; Reader reader; StringStream ss(json); - reader.Parse(ss, handler); + reader.Parse(ss, handler); - return 0; + return 0; } diff --git a/example/simplewriter/simplewriter.cpp b/example/simplewriter/simplewriter.cpp index 98e5b2c3..f8891504 100644 --- a/example/simplewriter/simplewriter.cpp +++ b/example/simplewriter/simplewriter.cpp @@ -31,5 +31,5 @@ int main() { cout << s.GetString() << endl; - return 0; + return 0; } diff --git a/example/tutorial/tutorial.cpp b/example/tutorial/tutorial.cpp index c0aca10c..fc96874d 100644 --- a/example/tutorial/tutorial.cpp +++ b/example/tutorial/tutorial.cpp @@ -1,156 +1,156 @@ // 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 "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output
+#include "rapidjson/document.h" // rapidjson's DOM-style API
+#include "rapidjson/prettywriter.h" // for stringify JSON
+#include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output
#include <cstdio>
using namespace rapidjson;
int main(int, char*[]) {
- ////////////////////////////////////////////////////////////////////////////
- // 1. Parse a JSON text string to a document.
+ ////////////////////////////////////////////////////////////////////////////
+ // 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);
+ 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.
+ 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;
+ // "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;
- }
+ // 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());
-
- // Note:
- //int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type.
- int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work.
- int z = a[0u].GetInt(); // This works too.
- (void)y;
- (void)z;
-
- // 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");
- FileStream f(stdout);
- PrettyWriter<FileStream> writer(f);
- document.Accept(writer); // Accept() traverses the DOM and generates Handler events.
-
- return 0;
+ 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());
+
+ // Note:
+ //int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type.
+ int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work.
+ int z = a[0u].GetInt(); // This works too.
+ (void)y;
+ (void)z;
+
+ // 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");
+ FileStream f(stdout);
+ PrettyWriter<FileStream> writer(f);
+ document.Accept(writer); // Accept() traverses the DOM and generates Handler events.
+
+ return 0;
}
|