prettyauto.cpp 2.2 KB

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