1 #include "json/json.h" 2 #include <cstdlib> 3 #include <iostream> 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 */ main()13int main() { 14 const std::string rawJson = "{\"Age\": 20, \"Name\": \"colin\"}"; 15 const int rawJsonLength = static_cast<int>(rawJson.length()); 16 JSONCPP_CONST 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 Json::CharReader* reader(builder.newCharReader()); 26 if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root, 27 &err)) { 28 std::cout << "error" << std::endl; 29 return EXIT_FAILURE; 30 } 31 delete reader; 32 } 33 const std::string name = root["Name"].asString(); 34 const int age = root["Age"].asInt(); 35 36 std::cout << name << std::endl; 37 std::cout << age << std::endl; 38 return EXIT_SUCCESS; 39 } 40