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.
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"
16 using namespace rapidjson
;
18 int main(int, char*[]) {
20 // Prevent Windows converting between CR+LF and LF
21 _setmode(_fileno(stdin
), _O_BINARY
); // NEW
22 _setmode(_fileno(stdout
), _O_BINARY
); // NEW
25 // Prepare reader and input stream.
27 GenericReader
<AutoUTF
<unsigned>, UTF8
<> > reader
; // CHANGED
28 char readBuffer
[65536];
29 FileReadStream
is(stdin
, readBuffer
, sizeof(readBuffer
));
30 AutoUTFInputStream
<unsigned, FileReadStream
> eis(is
); // NEW
32 // Prepare writer and output stream.
33 char writeBuffer
[65536];
34 FileWriteStream
os(stdout
, writeBuffer
, sizeof(writeBuffer
));
37 // Use the same Encoding of the input. Also use BOM according to input.
38 typedef AutoUTFOutputStream
<unsigned, FileWriteStream
> OutputStream
; // NEW
39 OutputStream
eos(os
, eis
.GetType(), eis
.HasBOM()); // NEW
40 PrettyWriter
<OutputStream
, UTF8
<>, AutoUTF
<unsigned> > writer(eos
); // CHANGED
42 // You may also use static bound encoding type, such as output to UTF-16LE with BOM
43 typedef EncodedOutputStream
<UTF16LE
<>,FileWriteStream
> OutputStream
; // NEW
44 OutputStream
eos(os
, true); // NEW
45 PrettyWriter
<OutputStream
, UTF8
<>, UTF16LE
<> > writer(eos
); // CHANGED
48 // JSON reader parse from the input stream and let writer generate the output.
49 //if (!reader.Parse<kParseValidateEncodingFlag>(is, writer)) {
50 if (!reader
.Parse
<kParseValidateEncodingFlag
>(eis
, writer
)) { // CHANGED
51 fprintf(stderr
, "\nError(%u): %s\n", static_cast<unsigned>(reader
.GetErrorOffset()), GetParseError_En(reader
.GetParseErrorCode()));