tutorial.cpp 6.2 KB

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