prettyauto.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // JSON pretty formatting example
  2. // This example can handle UTF-8/UTF-16LE/UTF-16BE/UTF-32LE/UTF-32BE.
  3. // The input firstly convert to UTF8, and then write to the original encoding with pretty formatting.
  4. #include <rtthread.h>
  5. #include "rapidjson/reader.h"
  6. #include "rapidjson/prettywriter.h"
  7. #include "rapidjson/filereadstream.h"
  8. #include "rapidjson/filewritestream.h"
  9. #include "rapidjson/encodedstream.h" // NEW
  10. #include "rapidjson/error/en.h"
  11. #ifdef _WIN32
  12. #include <fcntl.h>
  13. #include <io.h>
  14. #endif
  15. using namespace rapidjson;
  16. int pretty_auto(int, char*[]) {
  17. #ifdef _WIN32
  18. // Prevent Windows converting between CR+LF and LF
  19. _setmode(_fileno(stdin), _O_BINARY); // NEW
  20. _setmode(_fileno(stdout), _O_BINARY); // NEW
  21. #endif
  22. // Prepare reader and input stream.
  23. //Reader reader;
  24. GenericReader<AutoUTF<unsigned>, UTF8<> > reader; // CHANGED
  25. char readBuffer[1024];
  26. FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
  27. AutoUTFInputStream<unsigned, FileReadStream> eis(is); // NEW
  28. // Prepare writer and output stream.
  29. char writeBuffer[1024];
  30. FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
  31. #if 1
  32. // Use the same Encoding of the input. Also use BOM according to input.
  33. typedef AutoUTFOutputStream<unsigned, FileWriteStream> OutputStream; // NEW
  34. OutputStream eos(os, eis.GetType(), eis.HasBOM()); // NEW
  35. PrettyWriter<OutputStream, UTF8<>, AutoUTF<unsigned> > writer(eos); // CHANGED
  36. #else
  37. // You may also use static bound encoding type, such as output to UTF-16LE with BOM
  38. typedef EncodedOutputStream<UTF16LE<>,FileWriteStream> OutputStream; // NEW
  39. OutputStream eos(os, true); // NEW
  40. PrettyWriter<OutputStream, UTF8<>, UTF16LE<> > writer(eos); // CHANGED
  41. #endif
  42. // JSON reader parse from the input stream and let writer generate the output.
  43. //if (!reader.Parse<kParseValidateEncodingFlag>(is, writer)) {
  44. if (!reader.Parse<kParseValidateEncodingFlag>(eis, writer)) { // CHANGED
  45. fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
  46. return 1;
  47. }
  48. return 0;
  49. }
  50. MSH_CMD_EXPORT(pretty_auto, rapid json pretty auto example);