readFromString.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include "json/json.h"
  2. #include <iostream>
  3. #include <memory>
  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. */
  13. int main() {
  14. const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
  15. const auto rawJsonLength = static_cast<int>(rawJson.length());
  16. constexpr bool shouldUseOldWay = false;
  17. JSONCPP_STRING err;
  18. Json::Value root;
  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. std::cout << name << std::endl;
  34. std::cout << age << std::endl;
  35. return EXIT_SUCCESS;
  36. }