blob: c27bbd5ae57a29548c18823535082a524f3e0a58 [file] [log] [blame]
dota17e9ccbe02019-09-18 04:30:00 +08001#include "json/json.h"
2#include <iostream>
3/**
4 * \brief Parse a raw string into Value object using the CharReaderBuilder
Jordan Bayles2e33c212019-10-11 15:08:42 -07005 * class, or the legacy Reader class.
6 * Example Usage:
dota17e9ccbe02019-09-18 04:30:00 +08007 * $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
8 * $./readFromString
9 * colin
10 * 20
11 */
12int main() {
13 const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
Chen2983f5a2019-12-04 09:08:45 +080014 const auto rawJsonLength = static_cast<int>(rawJson.length());
dota17e9ccbe02019-09-18 04:30:00 +080015 constexpr bool shouldUseOldWay = false;
16 JSONCPP_STRING err;
17 Json::Value root;
18
19 if (shouldUseOldWay) {
20 Json::Reader reader;
21 reader.parse(rawJson, root);
22 } else {
23 Json::CharReaderBuilder builder;
24 const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
25 if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
26 &err)) {
27 std::cout << "error" << std::endl;
28 return EXIT_FAILURE;
29 }
30 }
31 const std::string name = root["Name"].asString();
32 const int age = root["Age"].asInt();
33
34 std::cout << name << std::endl;
35 std::cout << age << std::endl;
36 return EXIT_SUCCESS;
37}