1

Trying to serialize a class I have into a json string. Of course I can just write the strings manually, but I was hoping to utilize a the picojson library.

What I am trying to achieve is, given this class A

class A {
  public:
    int field1;
    string field2;
}

A a;
a.field1 = 1;
a.field2 = "example";

I want to convert this class instance "a" into a picojson object and then call picojson::serialize() to get the json string.

{"field1": 1, "field2": "example"}
penguins
  • 76
  • 8
  • Does [this](https://stackoverflow.com/questions/31121378/json-cpp-how-to-initialize-from-string-and-get-string-value) answer your question? – bhristov Jun 22 '20 at 17:49

1 Answers1

4

Well completely of the top of my head, and just by looking at the header file, it seems you need something like this

using namespace picojson;

object o;
o["field1"] = value(static_cast<double>(a.field1));
o["field2"] = value(a.field2);
std::cout << value(o);

or (what you actually asked for)

std::string s = value(o).serialize();
john
  • 85,011
  • 4
  • 57
  • 81
  • 1
    Well I've now tested the above code, and made one small correction (added the static_cast), so you should be good to go. – john Jun 22 '20 at 17:56