netheril96 / StaticJSON

Fast, direct and static typed parsing of JSON with C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Conversion of custom string class to std string

imtrobin opened this issue · comments

Hi, I have an external library, which defines the custom string class. I prefer not to touch its source code. So I wondering if there is a way to call a custom conversion function to convert the std string to custom string class while deserializing.

The implementation of string support is in include/staticjson/primitive_types.hpp, as

namespace staticjson 
{
template <>
class Handler<std::string> : public BaseHandler
{
private:
    std::string* m_value;

public:
    explicit Handler(std::string* v) : m_value(v) {}

    bool String(const char* str, SizeType length, bool) override
    {
        m_value->assign(str, length);
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "string"; }

    bool write(IHandler* out) const override
    {
        return out->String(m_value->data(), SizeType(m_value->size()), true);
    }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("string"), alloc);
    }
};
}

I think it is pretty obvious how to write the specialization for your own string class. Just remember to put the specialization in namespace staticjson, and put it before any usage of staticjson functions.

Thank you.