Rapidjson: Writing to Value is verbose

Created on 14 Jun 2017  路  6Comments  路  Source: Tencent/rapidjson

I've been slowly converting a codebase over to rapidjson.

My old code used to be:

void Class::addJson(Value& v) const {
v[Interface::JSON_KEY] = getStringData();
}

Now its:

void Class::addJson(Value& v, Value::AllocatorType& allocator) const {
Value key(Interface::JSON_KEY, allocator);
Value object(getStringData(), allocator);
v.AddMember(key, object, allocator);
}

Is there a shorter way? Otherwise another helper method :)

Most helpful comment

Yeah, I know. Still verbose. Just wondering if there was any shorter way. I'll just stick with my helper method.

In your special case (object is a std::string), you should then be able to use

  v.AddMember( StringRef(Interface::JSON_KEY), object, allocator );

see this AddMember overload, combined with the templated overload taking a StringRefType as name.

All 6 comments

Created a little helper method:

void Class::addString(Value& v, Value::AllocatorType& allocator, const std::string & key, const std::string & object) {
    Value keyValue(key, allocator);
    Value objectValue(object, allocator);
    v.AddMember(keyValue, objectValue, allocator);
}

May be written as a single line:

~cpp
v.AddMember(Value(key, allocator).Move(), Value(object, allocator).Move(), allocator);
~

Biggest question would be: What's the type/semantics of Interface::JSON_KEY?

Assuming that this is a global constant, you can avoid copying this string into the JSON and only reference it instead, see StringRef():

  v.AddMember( StringRef(Interface::JSON_KEY), Value(object, allocator).Move(), allocator );

In C++11, you don't need the call to Move() anymore.

"May be written as a single line"
Yeah, I know. Still verbose. Just wondering if there was any shorter way. I'll just stick with my helper method.

"What's the type/semantics of Interface::JSON_KEY?"
It's just a static const std::string.

Yeah, I know. Still verbose. Just wondering if there was any shorter way. I'll just stick with my helper method.

In your special case (object is a std::string), you should then be able to use

  v.AddMember( StringRef(Interface::JSON_KEY), object, allocator );

see this AddMember overload, combined with the templated overload taking a StringRefType as name.

Great that works.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lixiaofan0 picture lixiaofan0  路  3Comments

ns-osmolsky picture ns-osmolsky  路  4Comments

coderwenhao picture coderwenhao  路  3Comments

lasalvavida picture lasalvavida  路  5Comments

OlafvdSpek picture OlafvdSpek  路  6Comments