Search code examples
c++jsonenumsboost-propertytree

How to read enum from json in C++ using boost?


How to read an enum from json using read_json from boost? I know that I cand read an int and then compare it, but I would like to insert a string and convert it to the enum. Is this possible, or I shall create a function that does this (receive the string and return an int)?


Solution

  • The JSON Format doesn't have enums. So you either passe integers or strings. In both cases there is nothing automatic that will allow you to make a difference between other regular integers and strings. Furthermore conversion from string to enum in c++ always involve a translation table somewhere, there is no automatic way to do that.

    So yes you basically need to write custom code to handle your enum.

    You either chose integers and cast them to your enum type, or you chose strings and you use a conversion map to translate the strings to the right enum value.