File: object_iteration.cpp

package info (click to toggle)
valijson 1.0.3%2Brepack-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,756 kB
  • sloc: cpp: 19,769; sh: 134; makefile: 24
file content (69 lines) | stat: -rw-r--r-- 1,683 bytes parent folder | download | duplicates (3)
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
/**
 * @file
 *
 * @brief Demonstrates iteration over the members of an object
 *
 */

#include <iostream>

#include <json/json.h>
#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/utils/jsoncpp_utils.hpp>

using std::cerr;
using std::cout;
using std::endl;

template<typename AdapterType>
void iterateJsonObject(const AdapterType &adapter)
{
    if (!adapter.maybeObject()) {
        cout << "Not an object." << endl;
        return;
    }

    cout << "Object members:" << endl;

    // JSON objects are an unordered collection of key-value pairs,
    // so the members of the object may be printed in an order that is
    // different to that in the source JSON document.
    for (auto member : adapter.asObject()) {
        // The key is a std::string that can be accessed using 'first'
        cout << "  " << member.first << ": ";

        // The value is just another Adapter, and can be accessed using 'second'
        const AdapterType &value = member.second;
        if (value.maybeString()) {
            cout << value.asString();
        }

        cout << endl;
    }
}

void usingJsonCppWithTemplateFn(const char *filename)
{
    Json::Value value;
    if (!valijson::utils::loadDocument(filename, value)) {
        return;
    }

    valijson::adapters::JsonCppAdapter adapter(value);
    iterateJsonObject(adapter);
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        cerr << "Usage: " << endl;
        cerr << "  " << argv[0] << " <filename>" << endl;
        return 1;
    }

    cout << "-- Object iteration using jsoncpp via template function --" << endl;
    usingJsonCppWithTemplateFn(argv[1]);
    cout << endl;

    return 0;
}