JSonCpp - create a JSON file in C++

I have been tasked with creating functionality in C++(running on Linux) to create a JSON file. I have been able to create labels and data:pair for single elements, but am having difficulty with arrays. I have not found any documentation yet to discuss the steps required for this.
The library that I am using for this is JsonCpp.
The data consists of numbers and strings to be serialized to Json.

I am using keys for proper sorting. Not part of issue, but some background.

The template for my arrays is as follows:

“Array1” : X of (5 total arrays)
[
“Val1” : 256
“Val2” : 1,
“Val3” : 100,
“Object1” : X of (10 total objects)
{
“Val4” : 50.00
“Val5” : 85.00
}
“Array2” : X of (20 total arrays)
[
{
“Val6” : 0,
“Val7” : 0,
“Object2” :
{
“X” : 1,
“Y” : 2,
“Z” : 3,
}
“Object3” :
{
“X” : 5,
“Y” : 10,
“Z” : 15,
}
“Object4” :
{
“X” : 1000,
“Y” : 2000,
“Z” : 3000,
}
“Val8” : 10,
“Val9” : 19,
“Val10” : 0
}
]
]

Here is what I have put together, when ran, note that the array brackets do not appear around the second array. This is my main issue here with this now, How do I code the second array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void test1()
{
    Json::Value root;
	
	Json::Value& Array1 = root["Array1"];  // = pJson->Iteration[pJson->IterationLoop].c_str();
    {
	Json::Value& AVal = Array1[0];
    AVal["Val1"] = "256";
    AVal["Val2"] = "1";
    AVal["Val3"] = "100";
    Json::Value& UObject = AVal["Object1"];
    UObject["Val4"] =  "50.00";
    UObject["Val5"] = "85.00";
    Json::Value& SegArray = AVal["Array2"];
    {
    SegArray["Val6"] = "0";
    SegArray["Val7"] = "0";
    Json::Value& AObject = SegArray["Object2"];
    AObject["X"] = "1";
    AObject["Y"] = "2";
    AObject["Z"] = "3";
    Json::Value& SObject = SegArray["Object3"];
    SObject["X"] = "5";
    SObject["Y"] = "10";
    SObject["Z"] = "15";
    Json::Value& RObject = SegArray["Object4"];
    RObject["X"] = "1000";
    RObject["Y"] = "2000";
    RObject["Z"] = "3000";
    SegArray["Val8"] = ;
    SegArray["Val9"] = ;
    SegArray["Val10"] = ;
    }
}


Thank you.
Last edited on
from c++ side its just spitting out the text you want the way you want it.
there are probably json libraries, though its such a simple format for most things I don't know any I always just cook up a string...

I guess, what is giving you trouble? It looks like a pair of loops to crank it out?
What does the C++ data structure look like that you need to serialize to a json file?
nlohmann's json library can be used as a single #include (json.hpp).
https://github.com/nlohmann/json

It mainly uses a combination of std::map for objects, and std::vector for arrays.
For notes/examples of serialization, see: https://github.com/nlohmann/json#serialization--deserialization
Last edited on
Topic archived. No new replies allowed.