capitalize.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // JSON condenser exmaple
  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 : public BaseReaderHandler<UTF8<>, OutputHandler> {
  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(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 EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
  30. bool StartArray() { return out_.StartArray(); }
  31. bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
  32. OutputHandler& out_;
  33. std::vector<char> buffer_;
  34. private:
  35. CapitalizeFilter(const CapitalizeFilter&);
  36. CapitalizeFilter& operator=(const CapitalizeFilter&);
  37. };
  38. int main(int, char*[]) {
  39. // Prepare JSON reader and input stream.
  40. Reader reader;
  41. char readBuffer[65536];
  42. FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
  43. // Prepare JSON writer and output stream.
  44. char writeBuffer[65536];
  45. FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
  46. Writer<FileWriteStream> writer(os);
  47. // JSON reader parse from the input stream and let writer generate the output.
  48. CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
  49. if (!reader.Parse(is, filter)) {
  50. fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
  51. return 1;
  52. }
  53. return 0;
  54. }