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

Enhancement in EnumHandler #12

Closed elgatito closed 3 years ago

elgatito commented 3 years ago

Hello.

First of all, thanks you your library, which saved pretty much time for me!

While using Enum serializer, I have noticed that it is only possible to serialize string bash to enum: https://github.com/jorgen/json_struct/blob/master/include/json_struct.h#L4261

static inline Error to(T &to_type, ParseContext &context)
  {
    if (context.token.value_type == Type::String)
    {
      auto &strings = F::strings();
      for (size_t i = 0; i < strings.size(); i++)
      {
        const DataRef &ref = strings[i];
        if (ref.size == context.token.value.size)
        {
          if (memcmp(ref.data, context.token.value.data, ref.size) == 0)
          {
            to_type = static_cast<T>(i);
            return Error::NoError;
          }
        }
      }
    }
    return Error::IllegalDataValue;
  }

It would be very helpful if it become possible to serialize enum from int value, which is the enum value actually.

EnumHandler::to can be adjusted with another clause to parse number, something like this:

     else if (context.token.value_type == Type::Number)
     {
       int32_t tmp;
       const char *pointer;
       auto parse_error = Internal::ft::integer::to_integer(context.token.value.data, context.token.value.size, tmp, pointer);
       if (parse_error != Internal::ft::parse_string_error::ok || context.token.value.data == pointer)
         return Error::FailedToParseInt;

       to_type = static_cast<T>(tmp);
       return Error::NoError;
     }
jorgen commented 3 years ago

Nice! I will have a look at it.

jorgen commented 3 years ago

This is fixed by d28f8055fedc64ff97eac9d2b5564fe32dfb5807

elgatito commented 3 years ago

@jorgen Awesome! Works like a charm! Thanks