blob: 0b29a4e86174f067587d74d731d633e57785a188 [file] [log] [blame]
Haibo Huangb0bee822021-02-24 15:40:15 -08001#include "json/json.h"
2#include <iostream>
Elliott Hughes1601ea02021-12-07 09:43:38 -08003#include <memory>
Haibo Huangb0bee822021-02-24 15:40:15 -08004/**
5 * \brief Parse a raw string into Value object using the CharReaderBuilder
6 * class, or the legacy Reader class.
7 * Example Usage:
8 * $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
9 * $./readFromString
10 * colin
11 * 20
12 */
13int main() {
14 const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
15 const auto rawJsonLength = static_cast<int>(rawJson.length());
16 constexpr bool shouldUseOldWay = false;
17 JSONCPP_STRING err;
18 Json::Value root;
19
20 if (shouldUseOldWay) {
21 Json::Reader reader;
22 reader.parse(rawJson, root);
23 } else {
24 Json::CharReaderBuilder builder;
25 const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
26 if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
27 &err)) {
28 std::cout << "error" << std::endl;
29 return EXIT_FAILURE;
30 }
31 }
32 const std::string name = root["Name"].asString();
33 const int age = root["Age"].asInt();
34
35 std::cout << name << std::endl;
36 std::cout << age << std::endl;
37 return EXIT_SUCCESS;
38}