readFromString.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. */
  12. int 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. if (shouldUseOldWay) {
  19. Json::Reader reader;
  20. reader.parse(rawJson, root);
  21. } else {
  22. Json::CharReaderBuilder builder;
  23. const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
  24. if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
  25. &err)) {
  26. std::cout << "error" << std::endl;
  27. return EXIT_FAILURE;
  28. }
  29. }
  30. const std::string name = root["Name"].asString();
  31. const int age = root["Age"].asInt();
  32. std::cout << name << std::endl;
  33. std::cout << age << std::endl;
  34. return EXIT_SUCCESS;
  35. }