|
1 | 1 | #include "json/json.h"
|
2 | 2 | #include <iostream>
|
3 |
| -/* |
4 |
| -parse a string to Value object with CharReaderBuilder class or Reader class |
5 |
| -$g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString |
6 |
| -$./readFromString |
7 |
| -colin |
8 |
| -20 |
9 |
| -*/ |
| 3 | +/** |
| 4 | + * \brief Parse a raw string into Value object using the CharReaderBuilder |
| 5 | + * class, or the legacy Reader class. |
| 6 | + * Example Usage: |
| 7 | + * $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString |
| 8 | + * $./readFromString |
| 9 | + * colin |
| 10 | + * 20 |
| 11 | + */ |
10 | 12 | int main() {
|
11 |
| - std::string strRes = R"({"Age": 20, "Name": "colin"})"; |
12 |
| - auto nLen = (int)strRes.length(); |
| 13 | + const std::string rawJson = R"({"Age": 20, "Name": "colin"})"; |
| 14 | + const int rawJsonLength = static_cast<int>(rawJson.length()); |
| 15 | + constexpr bool shouldUseOldWay = false; |
13 | 16 | JSONCPP_STRING err;
|
14 | 17 | Json::Value root;
|
15 | 18 |
|
16 |
| -#if 0 // old way |
17 |
| - Json::Reader myreader; |
18 |
| - myreader.parse(strRes,root); |
19 |
| -#else // new way |
20 |
| - Json::CharReaderBuilder builder; |
21 |
| - std::unique_ptr<Json::CharReader> const reader(builder.newCharReader()); |
22 |
| - if (!reader->parse(strRes.c_str(), strRes.c_str() + nLen, &root, &err)) { |
23 |
| - std::cout << "error" << std::endl; |
24 |
| - return EXIT_FAILURE; |
| 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 | + } |
25 | 30 | }
|
26 |
| -#endif |
27 |
| - std::string strName = root["Name"].asString(); |
28 |
| - int strAge = root["Age"].asInt(); |
| 31 | + const std::string name = root["Name"].asString(); |
| 32 | + const int age = root["Age"].asInt(); |
29 | 33 |
|
30 |
| - std::cout << strName << std::endl; |
31 |
| - std::cout << strAge << std::endl; |
| 34 | + std::cout << name << std::endl; |
| 35 | + std::cout << age << std::endl; |
32 | 36 | return EXIT_SUCCESS;
|
33 | 37 | }
|
0 commit comments