1

I am codding in C++ and using JsonCPP. I have a class with 150+ variables and I would like to know if it is possible to convert all the variables to Json at once. I would like not to do this :

myClass.h

class myClass
{
   std::string var0;
   std::string var1;
   //...
   std::string var150;
}

main.cpp

int main() 
{
   Json::Value param;

   param["var0"] = var0;
   param["var1"] = var1;
   //...
   param["var150"] = var150;
}

Thanks for your tips.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
David Pham
  • 151
  • 1
  • 1
  • 15
  • Are you sure there's no way to refactor it? Maybe, you could benefit from inheritance, for instance? What kind of class is it, if you don't mind me asking? Just curious. I've never seen a class with so many variables. – FreeNickname Jul 25 '17 at 10:23
  • I am working with a vulnerability scanner API, Nessus. I need to create and configure a scan policy and there is a lot of variables in it. – David Pham Jul 25 '17 at 10:24
  • 2
    Are all the member variable the same type ? If yes, can't you use a ``std::map`` where the key would be the variable name ? You could then iterate over the map to serialise into JSON. – nefas Jul 25 '17 at 10:28
  • Why doesn't it have some sort of container, like a vector or a map, to store those variables? – Aziuth Jul 25 '17 at 10:29
  • Unfortunately the member variable arn't the same type. – David Pham Jul 25 '17 at 10:31
  • maybe a container and a variant (boost or std) would work ? – nefas Jul 25 '17 at 10:33
  • You [can't do that in C++](https://stackoverflow.com/questions/7143120/convert-string-to-variable-name-or-variable-type) and with a good reason. Use the container such as [std::map](http://en.cppreference.com/w/cpp/container/map) instead. – Ron Jul 25 '17 at 10:44
  • C++ doesn't have reflexivity, you have to use a library which simulates that as [boost hana](https://boostorg.github.io/hana/#tutorial-introspection-json) – Jarod42 Jul 25 '17 at 13:22

1 Answers1

2

One option is to create the structure in Google Protocol Buffers. You'll still need to list all the members once (in a .proto file instead of a .cpp file) but then you can use the protobuf library to convert to or from JSON, and it has other handy abilities too (e.g. iterate over the members, convert to a binary format, use with gRPC).

Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49