blob: 0b29a4e86174f067587d74d731d633e57785a188 [file] [log] [blame]
dota17e9ccbe02019-09-18 04:30:00 +08001#include "json/json.h"
2#include <iostream>
Jack Ulleryc39fbda2021-08-12 21:08:46 +00003#include <memory>
dota17e9ccbe02019-09-18 04:30:00 +08004/**
5 * \brief Parse a raw string into Value object using the CharReaderBuilder
Jordan Bayles2e33c212019-10-11 15:08:42 -07006 * class, or the legacy Reader class.
7 * Example Usage:
dota17e9ccbe02019-09-18 04:30:00 +08008 * $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"})";
Chen2983f5a2019-12-04 09:08:45 +080015 const auto rawJsonLength = static_cast<int>(rawJson.length());
dota17e9ccbe02019-09-18 04:30:00 +080016 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}