| 1 |
#include "json/json.h" |
| 2 |
#include <iostream> |
| 3 |
#include <memory> |
| 4 |
/** |
| 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 |
*/ |
| 13 |
int 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: " << err << 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 |
} |