capitalize.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // JSON condenser example
  2. // This example parses JSON from stdin with validation,
  3. // and re-output the JSON content to stdout with all string capitalized, and without whitespace.
  4. #include "rapidjson/reader.h"
  5. #include "rapidjson/writer.h"
  6. #include "rapidjson/filereadstream.h"
  7. #include "rapidjson/filewritestream.h"
  8. #include "rapidjson/error/en.h"
  9. #include <vector>
  10. #include <cctype>
  11. using namespace rapidjson;
  12. template<typename OutputHandler>
  13. struct CapitalizeFilter {
  14. CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
  15. bool Null() { return out_.Null(); }
  16. bool Bool(bool b) { return out_.Bool(b); }
  17. bool Int(int i) { return out_.Int(i); }
  18. bool Uint(unsigned u) { return out_.Uint(u); }
  19. bool Int64(int64_t i) { return out_.Int64(i); }
  20. bool Uint64(uint64_t u) { return out_.Uint64(u); }
  21. bool Double(double d) { return out_.Double(d); }
  22. bool String(const char* str, SizeType length, bool) {
  23. buffer_.clear();
  24. for (SizeType i = 0; i < length; i++)
  25. buffer_.push_back(static_cast<char>(std::toupper(str[i])));
  26. return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
  27. }
  28. bool StartObject() { return out_.StartObject(); }
  29. bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
  30. bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
  31. bool StartArray() { return out_.StartArray(); }
  32. bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
  33. OutputHandler& out_;
  34. std::vector<char> buffer_;
  35. private:
  36. CapitalizeFilter(const CapitalizeFilter&);
  37. CapitalizeFilter& operator=(const CapitalizeFilter&);
  38. };
  39. int main(int, char*[]) {
  40. // Prepare JSON reader and input stream.
  41. Reader reader;
  42. char readBuffer[65536];
  43. FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
  44. // Prepare JSON writer and output stream.
  45. char writeBuffer[65536];
  46. FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
  47. Writer<FileWriteStream> writer(os);
  48. // JSON reader parse from the input stream and let writer generate the output.
  49. CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
  50. if (!reader.Parse(is, filter)) {
  51. fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
  52. return 1;
  53. }
  54. return 0;
  55. }