How to Create a Json Object from Scratch in C++ Using Picojson. H

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"}
1

1 Answer

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();
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest