USCiLab / cereal

A C++11 library for serialization
BSD 3-Clause "New" or "Revised" License
4.17k stars 748 forks source link

JSON serialization bug #491

Open zhuebok opened 6 years ago

zhuebok commented 6 years ago

Next code works fine if I use XML or binary serializer, but JSON serializer performs invalid serialization, so deserializer fails on JSON string parse.

#include <string>
#include <sstream>

#include <boost/locale.hpp>

#include <cereal/cereal.hpp>
#include <cereal/types/string.hpp>
#include <cereal/archives/json.hpp>

struct Serializable
{
    std::wstring WideString;

    template<class A>
    void serialize( A &archive, const uint32_t )
    {
        archive( CEREAL_NVP( WideString ) );
    }
};

namespace cereal
{
    template<class A>
    std::string CEREAL_SAVE_MINIMAL_FUNCTION_NAME( A const &, const std::wstring &in )
    {
        return boost::locale::conv::utf_to_utf<char>( in );
    }

    template<class A>
    void CEREAL_LOAD_MINIMAL_FUNCTION_NAME( A const &, std::wstring &out, const std::string &in )
    {
        out = boost::locale::conv::utf_to_utf<wchar_t>( in );
    }
}

CEREAL_CLASS_VERSION( Serializable, 10 );
CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( std::wstring, cereal::specialization::non_member_load_save_minimal );

int main()
{
    std::string str;

    {
        Serializable s;
        s.WideString = L"WideStringValue";

        std::stringstream stream( std::ios::out | std::ios::binary );
        {
            cereal::JSONOutputArchive archive( stream );
            archive( CEREAL_NVP( s ) );
        }

        str = stream.str();
    }

    {
        std::stringstream stream( str, std::ios::in );
        cereal::JSONInputArchive archive( stream );

        Serializable s;
        archive( CEREAL_NVP( s ) );
    }

    return 0;
}
Persimelon commented 6 years ago

define this

namespace cereal
{
    template<class Traits, class Alloc> inline
        void prologue(JSONOutputArchive & ar, std::basic_string<wchar_t, Traits, Alloc> const &)
    {

    }
}
bkeys-RFA commented 5 years ago

Yes it should be noted that JSON serialization is not supported for std::wstring; should I make a separate issue regarding this? I tested it and XML doesn't support serialization of std::wstring either, however you can use binary serialization and it will work.