4

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!

jacob galam
  • 781
  • 9
  • 21
  • 1
    That would require [reflection](https://en.wikipedia.org/wiki/Reflection_(computer_programming)), which is something C++ is not able to do as of C++20. People get quite emotional about this topic, whether to add reflection to the language or not. As an anti-reflectionist I recommend you just pick the most convenient JSON library from [this list](https://en.cppreference.com/w/cpp/links/libs#Configuration). – nada May 11 '20 at 15:01
  • Well, you can write a minilanguage that generates at build time a C++ struct that knows how to (de)serialized itself. You can already do most of what you show in C++, but the member access is uglier (it's a tuple-like struct, so you need to use something like `std::get` instead of `person.name`) – Useless May 11 '20 at 15:12
  • @nada I understand your point, but: "Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at ***runtime***.".I want to use preprocess(something like define or template) and not change the struct at runtime.The answer that I linked is working but I don't want to write for every struct: properties = std::make_tuple... every time. Also I use Niels Lohmann JSON – jacob galam May 11 '20 at 15:29
  • Bad news then. The [nlohmann docs say](https://github.com/nlohmann/json#basic-usage) you still have to provide a `to_json` and `from_json` method for your structs. – nada May 11 '20 at 15:37
  • 2
    This definition of reflection is **Java-centric**. All reflection that exists **in Java** is run-time reflection. It doesn't have to be this way in other languages. When we say "reflection" in C++ context, we usually mean **compile-time reflection**, something entirely different from that Java-based definition. C++ doesn't have compile-time reflection, it is only vaguely planned for some indefinite future version. It will be "something like define or template" indeed when it exists, bit there is nothing like that now. – n. m. could be an AI May 11 '20 at 15:38

0 Answers0