1 #include "json/json.h" 2 #include <iostream> 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 */ main()12int main() { 13 const std::string rawJson = R"({"Age": 20, "Name": "colin"})"; 14 const auto 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 } 38