capitalize.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); }
  23. bool String(const char* str, SizeType length, bool) {
  24. buffer_.clear();
  25. for (SizeType i = 0; i < length; i++)
  26. buffer_.push_back(static_cast<char>(std::toupper(str[i])));
  27. return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
  28. }
  29. bool StartObject() { return out_.StartObject(); }
  30. bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
  31. bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
  32. bool StartArray() { return out_.StartArray(); }
  33. bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
  34. OutputHandler& out_;
  35. std::vector<char> buffer_;
  36. private:
  37. CapitalizeFilter(const CapitalizeFilter&);
  38. CapitalizeFilter& operator=(const CapitalizeFilter&);
  39. };
  40. int main(int, char*[]) {
  41. // Prepare JSON reader and input stream.
  42. Reader reader;
  43. char readBuffer[65536];
  44. FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
  45. // Prepare JSON writer and output stream.
  46. char writeBuffer[65536];
  47. FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
  48. Writer<FileWriteStream> writer(os);
  49. // JSON reader parse from the input stream and let writer generate the output.
  50. CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
  51. if (!reader.Parse(is, filter)) {
  52. fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
  53. return 1;
  54. }
  55. return 0;
  56. }