prettyauto.cpp 2.0 KB

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