Converting any struct to json automatic in C++

喜夏-厌秋 提交于 2021-02-11 06:24:43

问题


I am willing to convert any struct to json automatic without repeating code or variables in C++.

Desired result:

typedef JsonStruct<string, name, int, age> Person;  // not have to be template...

Person person;
person.name = "Jacob";
person.age = 16;

json personAsJson = person.toJson();
Person newPerson = Person::fromJson(personAsJson);
assert(newPerson == person);

I found this answer: https://stackoverflow.com/a/34165367/13277578

Which is really cool! but you still have to repeat the variable declaration... (struct fields & properties)

I tried so many things for so many times, but I still not even close to the desired result.

disclaimer: I am using Niels Lohmann JSON

Is it even possible to preprocess the fildes (or the properties) in the answer code to prevent repeating yourself in C++? Thanks!

来源:https://stackoverflow.com/questions/61732417/converting-any-struct-to-json-automatic-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!