I have a jsoncpp value that I want to serialize. The most straightforward way is like this:
Json::Value val; // population is left as an exercise for the reader
std::string str = Json::FastWriter().write(val);
The problem is that FastWriter
is deprecated, and I can't tolerate compiler warnings. According to the less-than-intuitive documentation, I'm supposed to use StreamWriterBuilder
instead:
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = "";
std::unique_ptr<Json::StreamWriter> writer( builder.newStreamWriter() );
std::ostringstream os;
writer->write(val, &os);
std::string str = os.str();
Surely this can't be "better"? I'm assuming the fault lies with me and there is a straightforward way to perform minimal serialization (without extraneous whitespace).
This shows a slightly more compact form (although it appears to simply wrap the above in a function call).
Json::StreamWriterBuilder builder;
builder["indentation"] = ""; // assume default for comments is None
std::string str = Json::writeString(builder, val);
Is that the right way now?
You're doing it the right way.
The second example is just a shorthand for the first — in both instances, a builder dynamically allocates a writer, the writer is used and then the writer is freed.
Why the older FastWriter
implementation was deprecated I could not say. Personally I miss it a bit. But a factory is more flexible and permits different implementations slotting into the same suite of functions. You'd have to ask the JsonCpp developers whether that was the core of their decision.