Skip to content

std::map and std::unordered_map serialization broken for keys of type std::u16string #5023

@mehecip

Description

@mehecip

Description

I am using a std::map<std::u16string, std::string> container.
I would expect that the serialized form for each of the items in the container is an json object {"key" : "value"}, instead it is a vector of vectors [["key", "value"]].

Manually converting the std::u16string to std::string in a to_json function does not help. Not converting it, makes it worse (the key would be an array of bytes - I suppose this is the root problem - 16bit chars are converted to 2 x 8 bit chars?).

Reproduction steps

#include <iostream>
#include <nlohmann/json.hpp>
#include <ostream>
#include <map>
#include <sstream>


#include <codecvt>
#include <locale>


std::string u16string_to_string(const std::u16string& input) {
    // Create a converter for UTF-16 to UTF-8
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
    return converter.to_bytes(input);
}
namespace std {
void to_json(nlohmann::json& j, const std::u16string& wide_str) {
    std::cout << "to_json  std::u16string called \n" ;
    j = u16string_to_string(wide_str);
}
}
int main() {
    std::map<std::u16string, std::string> ustrmap = {{std::u16string(u"key"), "value"}};
    nlohmann::json j = ustrmap;
    std::cout << "u16string serialization " << j << "\n";

    std::map<std::string, std::string> strmap = {{"key", "value"}};
    j = strmap;
    std::cout << "string serialization " << j;
    return 1;
}

Expected vs. actual results

actual result: [["key","value"]]
expected result: {"key":"value"}

Minimal code example

Error messages

Compiler and operating system

gcc12.2, gcc trunk

Library version

3.9.1, 3.11.1

Validation

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugsolution: proposed fixa fix for the issue has been proposed and waits for confirmationstate: please discussplease discuss the issue or vote for your favorite option

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions