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

this doest NOT support serialize a std::map with an int as its key #31

Closed yanzixiang closed 2 years ago

yanzixiang commented 2 years ago

Hi, I have been putting off making these TypeHandlers since then we have to include <map>, <set>, <unordered_set> in json_struct.h and suddenly everyone has has these includes just by including json_struct. I regret most of the includes in there already, but changing this can break user code, (I still have some members with spelling mistakes because chaning it will break code).

I have come up with this scheme where the TypeHandlers are guarded by their own include guards. So if you want the std::map TypeHandler then you will have to define JS_STL_MAP before including json_struct.h. The unit test should give you the idea: https://github.com/jorgen/json_struct/blob/master/tests/json-unordered-map.cpp#L4.

This is available in 3ddf92eef27b2b8388dcb06d43dd8bdf473d59bf.

_Originally posted by @jorgen in https://github.com/jorgen/json_struct/issues/27#issuecomment-1167994319_

for example;

std::map<int,std::map<int,std::string>> a;

JS::serializeStruct(a);

will give me an errer

invalid conversion from 'int' to 'const char*'

it seems that

/*!
 *  \brief Pointer to data
 *
 *  DataRef is used to refere to some data inside a json string. It holds the
 *  start posisition of the data, and its size.
 */
struct DataRef
{
  /*!
   * Constructs a null Dataref pointing to "" with size 0.
   */
  constexpr explicit DataRef()
    : data("")
    , size(0)
  {
  }

  /*!
   * Constructs a DataRef pointing to data and size.
   * \param data points to start of data.
   * \param size size of data.
   */
  constexpr explicit DataRef(const char *data, size_t size)
    : data(data)
    , size(size)
  {
  }

  /*!  Cobstructs a DataRef pointing to an array. This will \b NOT look for
   * the null terminator, but just initialize the DataRef to the size of the
   * array - 1. This function is intended to be used with string literals.
   * \param data  start of the data.
   */
  template <size_t N>
  constexpr explicit DataRef(const char (&data)[N])
    : data(data)
    , size(N - 1)
  {
  }

  explicit DataRef(const std::string &str)
    : data(&str[0])
    , size(str.size())
  {
  }

  explicit DataRef(const char *data)
    : data(data)
    , size(strlen(data))
  {
  }

  const char *data;
  size_t size;
};

does NOT privide an constructor which treat int as an input.

jorgen commented 2 years ago

yes, this will not work. I have not written an implicit conversion between int and string. The keys for a map have to be strings.