tutorial.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // Hello World example
  2. // This example shows basic usage of DOM-style API.
  3. #include "rapidjson/document.h" // rapidjson's DOM-style API
  4. #include "rapidjson/prettywriter.h" // for stringify JSON
  5. #include <cstdio>
  6. using namespace rapidjson;
  7. using namespace std;
  8. int main(int, char*[]) {
  9. ////////////////////////////////////////////////////////////////////////////
  10. // 1. Parse a JSON text string to a document.
  11. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
  12. printf("Original JSON:\n %s\n", json);
  13. Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator.
  14. #if 0
  15. // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream().
  16. if (document.Parse(json).HasParseError())
  17. return 1;
  18. #else
  19. // In-situ parsing, decode strings directly in the source string. Source must be string.
  20. char buffer[sizeof(json)];
  21. memcpy(buffer, json, sizeof(json));
  22. if (document.ParseInsitu(buffer).HasParseError())
  23. return 1;
  24. #endif
  25. printf("\nParsing to document succeeded.\n");
  26. ////////////////////////////////////////////////////////////////////////////
  27. // 2. Access values in document.
  28. printf("\nAccess values in document:\n");
  29. assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array.
  30. assert(document.HasMember("hello"));
  31. assert(document["hello"].IsString());
  32. printf("hello = %s\n", document["hello"].GetString());
  33. // Since version 0.2, you can use single lookup to check the existing of member and its value:
  34. Value::MemberIterator hello = document.FindMember("hello");
  35. assert(hello != document.MemberEnd());
  36. assert(hello->value.IsString());
  37. assert(strcmp("world", hello->value.GetString()) == 0);
  38. (void)hello;
  39. assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue().
  40. printf("t = %s\n", document["t"].GetBool() ? "true" : "false");
  41. assert(document["f"].IsBool());
  42. printf("f = %s\n", document["f"].GetBool() ? "true" : "false");
  43. printf("n = %s\n", document["n"].IsNull() ? "null" : "?");
  44. assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type.
  45. assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true.
  46. printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"]
  47. assert(document["pi"].IsNumber());
  48. assert(document["pi"].IsDouble());
  49. printf("pi = %g\n", document["pi"].GetDouble());
  50. {
  51. const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster.
  52. assert(a.IsArray());
  53. for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
  54. printf("a[%d] = %d\n", i, a[i].GetInt());
  55. int y = a[0].GetInt();
  56. (void)y;
  57. // Iterating array with iterators
  58. printf("a = ");
  59. for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
  60. printf("%d ", itr->GetInt());
  61. printf("\n");
  62. }
  63. // Iterating object members
  64. static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
  65. for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr)
  66. printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]);
  67. ////////////////////////////////////////////////////////////////////////////
  68. // 3. Modify values in document.
  69. // Change i to a bigger number
  70. {
  71. uint64_t f20 = 1; // compute factorial of 20
  72. for (uint64_t j = 1; j <= 20; j++)
  73. f20 *= j;
  74. document["i"] = f20; // Alternate form: document["i"].SetUint64(f20)
  75. assert(!document["i"].IsInt()); // No longer can be cast as int or uint.
  76. }
  77. // Adding values to array.
  78. {
  79. Value& a = document["a"]; // This time we uses non-const reference.
  80. Document::AllocatorType& allocator = document.GetAllocator();
  81. for (int i = 5; i <= 10; i++)
  82. a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's.
  83. // Fluent API
  84. a.PushBack("Lua", allocator).PushBack("Mio", allocator);
  85. }
  86. // Making string values.
  87. // This version of SetString() just store the pointer to the string.
  88. // So it is for literal and string that exists within value's life-cycle.
  89. {
  90. document["hello"] = "rapidjson"; // This will invoke strlen()
  91. // Faster version:
  92. // document["hello"].SetString("rapidjson", 9);
  93. }
  94. // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer.
  95. Value author;
  96. {
  97. char buffer2[10];
  98. int len = sprintf(buffer2, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string.
  99. author.SetString(buffer2, static_cast<SizeType>(len), document.GetAllocator());
  100. // Shorter but slower version:
  101. // document["hello"].SetString(buffer, document.GetAllocator());
  102. // Constructor version:
  103. // Value author(buffer, len, document.GetAllocator());
  104. // Value author(buffer, document.GetAllocator());
  105. memset(buffer2, 0, sizeof(buffer2)); // For demonstration purpose.
  106. }
  107. // Variable 'buffer' is unusable now but 'author' has already made a copy.
  108. document.AddMember("author", author, document.GetAllocator());
  109. assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null.
  110. ////////////////////////////////////////////////////////////////////////////
  111. // 4. Stringify JSON
  112. printf("\nModified JSON with reformatting:\n");
  113. StringBuffer sb;
  114. PrettyWriter<StringBuffer> writer(sb);
  115. document.Accept(writer); // Accept() traverses the DOM and generates Handler events.
  116. puts(sb.GetString());
  117. return 0;
  118. }