2019-09-18 04:30:00 +08:00
|
|
|
#include "json/json.h"
|
|
|
|
#include <iostream>
|
2021-08-12 21:08:46 +00:00
|
|
|
#include <memory>
|
2019-09-18 04:30:00 +08:00
|
|
|
/**
|
|
|
|
* \brief Parse a raw string into Value object using the CharReaderBuilder
|
2019-10-11 15:08:42 -07:00
|
|
|
* class, or the legacy Reader class.
|
|
|
|
* Example Usage:
|
2019-09-18 04:30:00 +08:00
|
|
|
* $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
|
|
|
|
* $./readFromString
|
|
|
|
* colin
|
|
|
|
* 20
|
|
|
|
*/
|
|
|
|
int main() {
|
|
|
|
const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
|
2019-12-04 09:08:45 +08:00
|
|
|
const auto rawJsonLength = static_cast<int>(rawJson.length());
|
2019-09-18 04:30:00 +08:00
|
|
|
constexpr bool shouldUseOldWay = false;
|
|
|
|
JSONCPP_STRING err;
|
|
|
|
Json::Value root;
|
|
|
|
|
|
|
|
if (shouldUseOldWay) {
|
|
|
|
Json::Reader reader;
|
|
|
|
reader.parse(rawJson, root);
|
|
|
|
} else {
|
|
|
|
Json::CharReaderBuilder builder;
|
|
|
|
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
|
|
|
|
if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
|
|
|
|
&err)) {
|
2024-09-10 04:51:35 +03:00
|
|
|
std::cout << "error: " << err << std::endl;
|
2019-09-18 04:30:00 +08:00
|
|
|
return EXIT_FAILURE;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const std::string name = root["Name"].asString();
|
|
|
|
const int age = root["Age"].asInt();
|
|
|
|
|
|
|
|
std::cout << name << std::endl;
|
|
|
|
std::cout << age << std::endl;
|
|
|
|
return EXIT_SUCCESS;
|
|
|
|
}
|