I'm trying to parse a JSON using this solution C++ JSON Serialization
but the difference is that i'm trying to parse directly to a C struct, so one of the issues is string assignment.
The error is this: error: incompatible types in assignment of 'int' to 'char [128]' obj->*(property.member) = a;
But if i switch from using a plain char array to using a std::string inside Cat struct, everything is ok. Any ideas on how can i make this work using a plain C style string ? i don't want to alter Cat struct.
#define STR_LEN 128
struct Cat {
char name [STR_LEN];
int age;
};
template<typename T>
void fromJson(const json& data, T &object) {
constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;
for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i){
constexpr auto property = std::get<i>(T::properties);
if (data.contains(property.name))
{
auto *obj = object.c; // the Cat inner object
if(data[property.name].is_string())
{
const char *str = data[property.name].dump().c_str();
std::cout << " is string > " << str << std::endl;
// strncpy(&(obj->*(property.member)), str, STR_LEN);
}
else
{
std::cout << data[property.name] << std::endl;
int a = data[property.name];
obj->*(property.member) = a;
// obj->*(property.member) = data[property.name];
}
}
});
}
class CatParser {
public:
Cat *c;
CatParser() {}
CatParser(Cat *cat): c(cat) { }
constexpr static auto properties = std::make_tuple(
property(&Cat::name, "name"), property(&Cat::age, "age"));
};
int main() {
json j;
j["name"] = "Kitty";
j["age"] = 3;
Cat c;
CatParser cp(&c);
fromJson<CatParser>(j, cp);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire