include json json include iostream using namespace std void output con

 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <json/json.h>
#include <iostream>
using namespace std;
void output(const Json::Value & value)
{
// querying the json object is very simple
std::cout << value["hello"];
std::cout << value["number"];
std::cout << value["array"][0] << value["array"][1];
std::cout << value["object"]["hello"];
}
int main(int argc, char **argv) {
// ---- create from scratch ----
Json::Value fromScratch;
Json::Value array;
array.append("hello");
array.append("world");
fromScratch["hello"] = "world";
fromScratch["number"] = 2;
fromScratch["array"] = array;
fromScratch["object"]["hello"] = "world";
output(fromScratch);
// write in a nice readible way
Json::StyledWriter styledWriter;
std::cout << styledWriter.write(fromScratch);
// ---- parse from string ----
// write in a compact way
Json::FastWriter fastWriter;
std::string jsonMessage = fastWriter.write(fromScratch);
Json::Value parsedFromString;
Json::Reader reader;
bool parsingSuccessful = reader.parse(jsonMessage, parsedFromString);
if (parsingSuccessful)
{
std::cout << styledWriter.write(parsedFromString) << std::endl;
}
return 0;
}
/*
zen@debian:~$ g++ main.cpp -o main -I/usr/include/jsoncpp -ljsoncpp
zen@debian:~$ ./main
"world"
2
"hello"
"world"
"world"
{
"array" : [ "hello", "world" ],
"hello" : "world",
"number" : 2,
"object" : {
"hello" : "world"
}
}
{
"array" : [ "hello", "world" ],
"hello" : "world",
"number" : 2,
"object" : {
"hello" : "world"
}
}
*/