Search code examples
c++jsoncpp

Json::Value as private class member


I'm writing a C++ class for Reading/Writing strings from/to a json file using the jsoncpp lib. My question is if it's possible to create a Json::Value private member for my class and use this every time I need to read/write instead of creating a new Json::Value inside every function?

If so, how can I initialize it in the constructor and access it inside every function?


Solution

  • You don't need any special initialization for the Json::Value. You can make it a private member variable and use it like any other member variable.

    Here's an example where I've added support for streaming from/to istream/ostream objects and a few member functions to demonstrate access to specific fields:

    #include "json/json.h"
    
    #include <fstream>
    #include <iostream>
    
    class YourClass {
    public:
        // two public accessors:
        double getTemp() const { return json_value["Temp"].asDouble(); }
        void setTemp(double value) { json_value["Temp"] = value; }
    
    private:
        Json::Value json_value;
    
        friend std::istream& operator>>(std::istream& is, YourClass& yc) {
            return is >> yc.json_value;
        }
        friend std::ostream& operator<<(std::ostream& os, const YourClass& yc) {
            return os << yc.json_value;
        }
    };
    
    int main() {
        YourClass yc;
    
        if(std::ifstream file("some_file.json"); file) {
            file >> yc;      // read file
            std::cout << yc; // print result to screen
    
            // use public member functions
            std::cout << yc.getTemp() << '\n';
            yc.setTemp(6.12);
            std::cout << yc.getTemp() << '\n';
        }
    }
    

    Edit: I was asked to explain the if statement and it means if( init-statement ; condition ) (added in C++17) which becomes approximately the same as this:

    { // scope of `file`
        std::ifstream file("some_file.json");
    
        if(file) { // test that `file` is in a good state
            // ... 
        }
    } // end of scope of `file`