Stream

In RapidJSON, rapidjson::Stream is a concept for reading/writing JSON. Here we'll first show you how to use provided streams. And then see how to create a custom stream.

Memory Streams

Memory streams store JSON in memory.

StringStream (Input)

StringStream is the most basic input stream. It represents a complete, read-only JSON stored in memory. It is defined in rapidjson/rapidjson.h.

#include "rapidjson/document.h" // will include "rapidjson/rapidjson.h"
using namespace rapidjson;
// ...
const char json[] = "[1, 2, 3, 4]";
StringStream s(json);

Since this is very common usage, Document::Parse(const char*) is provided to do exactly the same as above:

// ...
const char json[] = "[1, 2, 3, 4]";
d.Parse(json);

Note that, StringStream is a typedef of GenericStringStream<UTF8<> >, user may use another encodings to represent the character set of the stream.

StringBuffer (Output)

StringBuffer is a simple output stream. It allocates a memory buffer for writing the whole JSON. Use GetString() to obtain the buffer.

#include "rapidjson/stringbuffer.h"
#include <rapidjson/writer.h>
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
const char* output = buffer.GetString();

When the buffer is full, it will increases the capacity automatically. The default capacity is 256 characters (256 bytes for UTF8, 512 bytes for UTF16, etc.). User can provide an allocator and an initial capacity.

StringBuffer buffer1(0, 1024); // Use its allocator, initial size = 1024
StringBuffer buffer2(allocator, 1024);

By default, StringBuffer will instantiate an internal allocator.

Similarly, StringBuffer is a typedef of GenericStringBuffer<UTF8<> >.

File Streams

When parsing a JSON from file, you may read the whole JSON into memory and use StringStream above.

However, if the JSON is big, or memory is limited, you can use FileReadStream. It only read a part of JSON from file into buffer, and then let the part be parsed. If it runs out of characters in the buffer, it will read the next part from file.

FileReadStream (Input)

FileReadStream reads the file via a FILE pointer. And user need to provide a buffer.

#include "rapidjson/filereadstream.h"
#include <cstdio>
using namespace rapidjson;
FILE* fp = fopen("big.json", "rb"); // non-Windows use "r"
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);

Different from string streams, FileReadStream is byte stream. It does not handle encodings. If the file is not UTF-8, the byte stream can be wrapped in a EncodedInputStream. We will discuss more about this later in this tutorial.

Apart from reading file, user can also use FileReadStream to read stdin.

FileWriteStream (Output)

FileWriteStream is buffered output stream. Its usage is very similar to FileReadStream.

#include "rapidjson/filewritestream.h"
#include <rapidjson/writer.h>
#include <cstdio>
using namespace rapidjson;
d.Parse(json);
// ...
FILE* fp = fopen("output.json", "wb"); // non-Windows use "w"
char writeBuffer[65536];
FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
d.Accept(writer);
fclose(fp);

It can also redirect the output to stdout.

iostream Wrapper

Due to users' requests, RapidJSON also provides official wrappers for std::basic_istream and std::basic_ostream. However, please note that the performance will be much lower than the other streams above.

IStreamWrapper

IStreamWrapper wraps any class derived from std::istream, such as std::istringstream, std::stringstream, std::ifstream, std::fstream, into RapidJSON's input stream.

#include <rapidjson/istreamwrapper.h>
#include <fstream>
using namespace rapidjson;
using namespace std;
ifstream ifs("test.json");
IStreamWrapper isw(ifs);
d.ParseStream(isw);

For classes derived from std::wistream, use WIStreamWrapper.

OStreamWrapper

Similarly, OStreamWrapper wraps any class derived from std::ostream, such as std::ostringstream, std::stringstream, std::ofstream, std::fstream, into RapidJSON's input stream.

#include <rapidjson/ostreamwrapper.h>
#include <rapidjson/writer.h>
#include <fstream>
using namespace rapidjson;
using namespace std;
d.Parse(json);
// ...
ofstream ofs("output.json");
OStreamWrapper osw(ofs);
d.Accept(writer);

For classes derived from std::wostream, use WOStreamWrapper.

Encoded Streams

Encoded streams do not contain JSON itself, but they wrap byte streams to provide basic encoding/decoding function.

As mentioned above, UTF-8 byte streams can be read directly. However, UTF-16 and UTF-32 have endian issue. To handle endian correctly, it needs to convert bytes into characters (e.g. wchar_t for UTF-16) while reading, and characters into bytes while writing.

Besides, it also need to handle byte order mark (BOM). When reading from a byte stream, it is needed to detect or just consume the BOM if exists. When writing to a byte stream, it can optionally write BOM.

If the encoding of stream is known during compile-time, you may use EncodedInputStream and EncodedOutputStream. If the stream can be UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE JSON, and it is only known in runtime, you may use AutoUTFInputStream and AutoUTFOutputStream. These streams are defined in rapidjson/encodedstream.h.

Note that, these encoded streams can be applied to streams other than file. For example, you may have a file in memory, or a custom byte stream, be wrapped in encoded streams.

EncodedInputStream

EncodedInputStream has two template parameters. The first one is a Encoding class, such as UTF8, UTF16LE, defined in rapidjson/encodings.h. The second one is the class of stream to be wrapped.

#include "rapidjson/filereadstream.h" // FileReadStream
#include "rapidjson/encodedstream.h" // EncodedInputStream
#include <cstdio>
using namespace rapidjson;
FILE* fp = fopen("utf16le.json", "rb"); // non-Windows use "r"
char readBuffer[256];
FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
EncodedInputStream<UTF16LE<>, FileReadStream> eis(bis); // wraps bis into eis
Document d; // Document is GenericDocument<UTF8<> >
d.ParseStream<0, UTF16LE<> >(eis); // Parses UTF-16LE file into UTF-8 in memory
fclose(fp);

EncodedOutputStream

EncodedOutputStream is similar but it has a bool putBOM parameter in the constructor, controlling whether to write BOM into output byte stream.

#include "rapidjson/filewritestream.h" // FileWriteStream
#include "rapidjson/encodedstream.h" // EncodedOutputStream
#include <rapidjson/writer.h>
#include <cstdio>
Document d; // Document is GenericDocument<UTF8<> >
// ...
FILE* fp = fopen("output_utf32le.json", "wb"); // non-Windows use "w"
char writeBuffer[256];
FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer));
typedef EncodedOutputStream<UTF32LE<>, FileWriteStream> OutputStream;
OutputStream eos(bos, true); // Write BOM
Writer<OutputStream, UTF8<>, UTF32LE<>> writer(eos);
d.Accept(writer); // This generates UTF32-LE file from UTF-8 in memory
fclose(fp);

AutoUTFInputStream

Sometimes an application may want to handle all supported JSON encoding. AutoUTFInputStream will detection encoding by BOM first. If BOM is unavailable, it will use characteristics of valid JSON to make detection. If neither method success, it falls back to the UTF type provided in constructor.

Since the characters (code units) may be 8-bit, 16-bit or 32-bit. AutoUTFInputStream requires a character type which can hold at least 32-bit. We may use unsigned, as in the template parameter:

#include "rapidjson/filereadstream.h" // FileReadStream
#include "rapidjson/encodedstream.h" // AutoUTFInputStream
#include <cstdio>
using namespace rapidjson;
FILE* fp = fopen("any.json", "rb"); // non-Windows use "r"
char readBuffer[256];
FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
AutoUTFInputStream<unsigned, FileReadStream> eis(bis); // wraps bis into eis
Document d; // Document is GenericDocument<UTF8<> >
d.ParseStream<0, AutoUTF<unsigned> >(eis); // This parses any UTF file into UTF-8 in memory
fclose(fp);

When specifying the encoding of stream, uses AutoUTF<CharType> as in ParseStream() above.

You can obtain the type of UTF via UTFType GetType(). And check whether a BOM is found by HasBOM()

AutoUTFOutputStream

Similarly, to choose encoding for output during runtime, we can use AutoUTFOutputStream. This class is not automatic per se. You need to specify the UTF type and whether to write BOM in runtime.

using namespace rapidjson;
void WriteJSONFile(FILE* fp, UTFType type, bool putBOM, const Document& d) {
char writeBuffer[256];
FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer));
OutputStream eos(bos, type, putBOM);
d.Accept(writer);
}

AutoUTFInputStream and AutoUTFOutputStream is more convenient than EncodedInputStream and EncodedOutputStream. They just incur a little bit runtime overheads.

Custom Stream

In addition to memory/file streams, user can create their own stream classes which fits RapidJSON's API. For example, you may create network stream, stream from compressed file, etc.

RapidJSON combines different types using templates. A class containing all required interface can be a stream. The Stream interface is defined in comments of rapidjson/rapidjson.h:

concept Stream {
typename Ch; //!< Character type of the stream.
//! Read the current character from stream without moving the read cursor.
Ch Peek() const;
//! Read the current character from stream and moving the read cursor to next character.
Ch Take();
//! Get the current read cursor.
//! \return Number of characters read from start.
size_t Tell();
//! Begin writing operation at the current read pointer.
//! \return The begin writer pointer.
Ch* PutBegin();
//! Write a character.
void Put(Ch c);
//! Flush the buffer.
void Flush();
//! End the writing operation.
//! \param begin The begin write pointer returned by PutBegin().
//! \return Number of characters written.
size_t PutEnd(Ch* begin);
}

For input stream, they must implement Peek(), Take() and Tell(). For output stream, they must implement Put() and Flush(). There are two special interface, PutBegin() and PutEnd(), which are only for in situ parsing. Normal streams do not implement them. However, if the interface is not needed for a particular stream, it is still need to a dummy implementation, otherwise will generate compilation error.

Example: istream wrapper

The following example is a simple wrapper of std::istream, which only implements 3 functions.

class MyIStreamWrapper {
public:
typedef char Ch;
MyIStreamWrapper(std::istream& is) : is_(is) {
}
Ch Peek() const { // 1
int c = is_.peek();
return c == std::char_traits<char>::eof() ? '\0' : (Ch)c;
}
Ch Take() { // 2
int c = is_.get();
return c == std::char_traits<char>::eof() ? '\0' : (Ch)c;
}
size_t Tell() const { return (size_t)is_.tellg(); } // 3
Ch* PutBegin() { assert(false); return 0; }
void Put(Ch) { assert(false); }
void Flush() { assert(false); }
size_t PutEnd(Ch*) { assert(false); return 0; }
private:
MyIStreamWrapper(const MyIStreamWrapper&);
MyIStreamWrapper& operator=(const MyIStreamWrapper&);
std::istream& is_;
};

User can use it to wrap instances of std::stringstream, std::ifstream.

const char* json = "[1,2,3,4]";
std::stringstream ss(json);
MyIStreamWrapper is(ss);

Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library.

Example: ostream wrapper

The following example is a simple wrapper of std::istream, which only implements 2 functions.

class MyOStreamWrapper {
public:
typedef char Ch;
MyOStreamWrapper(std::ostream& os) : os_(os) {
}
Ch Peek() const { assert(false); return '\0'; }
Ch Take() { assert(false); return '\0'; }
size_t Tell() const { }
Ch* PutBegin() { assert(false); return 0; }
void Put(Ch c) { os_.put(c); } // 1
void Flush() { os_.flush(); } // 2
size_t PutEnd(Ch*) { assert(false); return 0; }
private:
MyOStreamWrapper(const MyOStreamWrapper&);
MyOStreamWrapper& operator=(const MyOStreamWrapper&);
std::ostream& os_;
};

User can use it to wrap instances of std::stringstream, std::ofstream.

// ...
std::stringstream ss;
MyOStreamWrapper os(ss);
Writer<MyOStreamWrapper> writer(os);
d.Accept(writer);

Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library.

Summary

This section describes stream classes available in RapidJSON. Memory streams are simple. File stream can reduce the memory required during JSON parsing and generation, if the JSON is stored in file system. Encoded streams converts between byte streams and character streams. Finally, user may create custom streams using a simple interface.

Stream
Concept for reading and writing characters.
rapidjson::BasicOStreamWrapper
Wrapper of std::basic_ostream into RapidJSON's Stream concept.
Definition: ostreamwrapper.h:45
document.h
rapidjson::EncodedInputStream
Input byte stream wrapper with a statically bound encoding.
Definition: encodedstream.h:39
rapidjson::GenericStringStream
Read-only string stream.
Definition: fwd.h:47
rapidjson::GenericDocument::ParseStream
GenericDocument & ParseStream(InputStream &is)
Parse JSON text from an input stream (with Encoding conversion)
Definition: document.h:2626
rapidjson::FileWriteStream
Wrapper of C file stream for output using fwrite().
Definition: filewritestream.h:32
rapidjson::FileReadStream
File byte stream for input using fread().
Definition: filereadstream.h:34
rapidjson::BasicIStreamWrapper
Wrapper of std::basic_istream into RapidJSON's Stream concept.
Definition: istreamwrapper.h:49
rapidjson::AutoUTF
Dynamically select encoding according to stream's runtime-specified UTF encoding type.
Definition: encodings.h:615
rapidjson::GenericDocument::Parse
GenericDocument & Parse(const typename SourceEncoding::Ch *str)
Parse JSON text from a read-only string (with Encoding conversion)
Definition: document.h:2692
rapidjson::StringBuffer
GenericStringBuffer< UTF8< char >, CrtAllocator > StringBuffer
String buffer with UTF8 encoding.
Definition: fwd.h:59
rapidjson::GenericDocument
A document for parsing JSON text as DOM.
Definition: document.h:69
rapidjson::Writer
JSON writer.
Definition: fwd.h:95
rapidjson::UTFType
UTFType
Runtime-specified UTF encoding type of a stream.
Definition: encodings.h:603
rapidjson::Document
GenericDocument< UTF8<> > Document
GenericDocument with UTF8 encoding.
Definition: document.h:2873
rapidjson::AutoUTFOutputStream
Output stream wrapper with dynamically bound encoding and automatic encoding detection.
Definition: encodedstream.h:233
rapidjson
main RapidJSON namespace
Definition: rapidjson.h:409
rapidjson::AutoUTFInputStream
Input stream wrapper with dynamically bound encoding and automatic encoding detection.
Definition: encodedstream.h:135
rapidjson::UTF16LE
UTF-16 little endian encoding.
Definition: encodings.h:342