dota17 | e9ccbe0 | 2019-09-18 04:30:00 +0800 | [diff] [blame] | 1 | #include "json/json.h" |
| 2 | #include <iostream> |
| 3 | /** |
| 4 | * \brief Parse a raw string into Value object using the CharReaderBuilder |
Jordan Bayles | 2e33c21 | 2019-10-11 15:08:42 -0700 | [diff] [blame^] | 5 | * class, or the legacy Reader class. |
| 6 | * Example Usage: |
dota17 | e9ccbe0 | 2019-09-18 04:30:00 +0800 | [diff] [blame] | 7 | * $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString |
| 8 | * $./readFromString |
| 9 | * colin |
| 10 | * 20 |
| 11 | */ |
| 12 | int main() { |
| 13 | const std::string rawJson = R"({"Age": 20, "Name": "colin"})"; |
| 14 | const int rawJsonLength = static_cast<int>(rawJson.length()); |
| 15 | 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 | } |