2

I've just begun using RapidJSON; currently, I've got a STL map of strings; and I want to represent it as JSON.

So far, I've done this:

using JSONDocument = rapidjson::GenericDocument<rapidjson::UTF8<>>;
using JSONValue = rapidjson::GenericValue<rapidjson::UTF8<>>;

    JSONDocument jsonRoot(rapidjson::kArrayType);
        for (auto const &kv : localeMap) {
            std::string key = kv.first;
            std::replace(key.begin(), key.end(), ' ','_');
            boost::to_lower(key);
            JSONValue k(rapidjson::kObjectType);
            JSONValue v(rapidjson::kObjectType);
            k.SetString(key,jsonRoot.GetAllocator());
            v.SetString(kv.second,jsonRoot.GetAllocator());

            JSONValue kv_(rapidjson::kObjectType);
            kv_.AddMember(k,v,jsonRoot.GetAllocator());
            jsonRoot.PushBack(kv_, jsonRoot.GetAllocator());
        }

And it works, but that looks terribly clunky to me. I cannot figure out if there's a better/shorter/more performant way of doing this... I've tried several variations of trying to create the object in place but they either don't compile or crash at runtime.

Any hints?

  • Are you locked into RapidJSON? nlohmann::json makes it [really easy](https://github.com/nlohmann/json#conversion-from-stl-containers) – Shawn Jul 20 '18 at 00:18
  • Have you tried [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer) You don't need to write any code to serialize a std::map. – Martin York Jul 23 '18 at 19:19

1 Answers1

4
        JSONValue k(rapidjson::kObjectType);
        JSONValue v(rapidjson::kObjectType);
        k.SetString(key,jsonRoot.GetAllocator());
        v.SetString(kv.second,jsonRoot.GetAllocator());

Can be simplified as :

        JSONValue k(key, jsonRoot.GetAllocator());
        JSONValue v(kv.second, jsonRoot.GetAllocator());

For a performance enhancement, you may reserve the size of array type before multiple PushBack():

jsonRoot.Reserve(localMap.size(), jsonRoot.GetAllocator());

And if all you need is a JSON, you may use SAX API (rapidjson::Writer) instead.

Milo Yip
  • 4,902
  • 2
  • 25
  • 27