Search code examples
c++jsonjsoncpp

How to read JSON file which has values with parameters in C++


I'm trying to read in a JSON file using C++. In the file i have key value pairs. And in the value, I am passing number of values with different parameters.

Is this approach is correct? Please suggest if there is any modifications required?

approach1:

"test_details" : {
        "testd" : "1",
        "testvalue":["one", "two(param1, para2)", "three(param1, param2, param3)"]
    }

approach2:

"test_details" : {
        "testd" : "1",
        "testvalue":"one"
    },
    {
        "testd" : "2",
        "testvalue":"two(param1, para2)"
    },
    {
        "testd" : "3",
        "testvalue":"three(param1, param2, param3)"
    }

Thank you


Solution

  • Yes it is possible to parse that json into an object. I highly prefer the second approach. Say you go with the second approach, you can create a TestCase class that looks look like:

    class TestCase {
    public:
       std::string id; 
       std::string value; 
       // std::vector<std::string> values; // this will hold multiple values for one test case
    }
    
    class TestDetails { public: std::vector<TestCase> };
    

    An object of this class can be constructed by deserializing your json payload. And vice versa to get the json serialization result.

    Check this library for parsing json in C++. There are plenty of solutions for json parsing, the library I linked is a personal preference.