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 :)
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.
Most helpful comment
In your special case (
objectis astd::string), you should then be able to usesee this
AddMemberoverload, combined with the templated overload taking aStringRefTypeas name.