There is two solutions.
Do it manually
you can provide a function that takes a json::value and return the object of your type:
User fromJson(json::value data) {
return User{data[U("username")].as_string(), data[U("info")].as_string()};
}
Do it automatically
There is no reflection in C++. True. But if the compiler can't provide you with metadata, you can provide it yourself.
Let's start by making a propery struct:
template<typename Class, typename T>
struct Property {
constexpr Property(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}
using Type = T;
T Class::*member;
const char* name;
};
Ok, now we have the building block of our compile-time introspection system.
Now in your class user, add your metadata:
struct User {
constexpr static auto properties = std::make_tuple(
Property<User, std::string>{&User::username, "username"},
Property<User, std::string>{&User::info, "info"}
);
private:
std::string username;
std::string info;
};
Now that you have the desired metadata, you can iterate through it by recursion:
template<std::size_t iteration, typename T>
void doSetData(T&& object, const json::value& data) {
// get the property
constexpr auto property = std::get<iteration>(std::decay_t<T>::properties);
// get the type of the property
using Type = typename decltype(property)::Type;
// set the value to the member
object.*(property.member) = asAny<Type>(data[U(property.name)]);
}
template<std::size_t iteration, typename T, typename = std::enable_if_t<(iteration > 0)>>
void setData(T&& object, const json::value& data) {
doSetData<iteration>(object, data);
// next iteration
setData<iteration - 1>(object, data);
}
template<std::size_t iteration, typename T, typename = std::enable_if_t<(iteration == 0)>>
void setData(T&& object, const json::value& data) {
doSetData<iteration>(object, data);
}
template<typename T>
T fromJson(Json::Value data) {
T object;
setData<std::tuple_size<decltype(T::properties)>::value - 1>(object, data);
return object;
}
That will do the trick.
I did not test this code, so if you have trouble, tell me in the comments.
Note that you will need to write the asAny function. It's just a function that takes a Json::Value and call the right as_... function, or another fromJson ;)