Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the way to replace jsoncpp FastWriter with Streambuilder?

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?

like image 876
jwm Avatar asked Dec 23 '22 02:12

jwm


2 Answers

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.

like image 144
Lightness Races in Orbit Avatar answered Dec 25 '22 15:12

Lightness Races in Orbit


If you always want to write with the same settings (e.g. your ["indentation"] = ""), you can supply a Json::Value representing the settings to Json::StreamWriterBuilder::setDefault, then writing strings doesn't need to name Json::StreamWriterBuilder again (but does default construct one)

Startup

Json::Value streamWriterSettings{R"({ "indentation" : "" })"};
Json::StreamWriterBuilder::setDefault(&streamWriterSettings);

Usage

std::string str = Json::writeString({}, val);
like image 35
Caleth Avatar answered Dec 25 '22 14:12

Caleth