jorgen / json_struct

json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa
Other
422 stars 57 forks source link

Cannot use a std::unordered_map with integer keys #62

Closed gerwaric closed 1 month ago

gerwaric commented 1 month ago

I'm using json_struct 1.0.1 with MSVC 2022 (so JS_STD_UNORDERED_MAP is 1) and this structure is giving me problems:

struct test_struct {
    std::unordered_map<int, std::string> test_map;
    JS_OBJ(test_map);
};

This is the error the compiler is giving me:

error C2440: 'initializing': cannot convert from 'initializer list' to 'Key'
    with
    [
        Key=int
    ]
json_struct.h(8093): note: The initializer contains too many elements

The error goes away if I change the structure to use std::unordered_map<std::string, std::string>. It looks like the problem is in the TypeHandlerMap template, because the key is constructed with Key key(str.data(), str.size()), which won't work for numeric types.

Do you think this is worth the trouble of addressing in json_struct.h, or should I write my own type handler than converts back and forth from integer to string keys?

jorgen commented 1 month ago

yes, this does not work, but its just because the json will be in the form of

{
 "1": "hello",
 "2": "world"
}

Ie the keys have to be serialized to string regardless since the keys in json have to be strings in dictionaries. It should be pretty easy to create a typehandler that would take a map with an int type as key. Check out: https://github.com/jorgen/json_struct/blob/19a71df0df00da616865eb0a885627ccbe0ec5de/include/json_struct/json_struct.h#L8077 https://github.com/jorgen/json_struct/blob/master/examples/08_custom_types.cpp

gerwaric commented 1 month ago

Thanks for the response. I have been away from working with json and forgot that the keys will always be strings. It will be easy enough to write a type handler.