json_utils.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #pragma once
  2. #include <map>
  3. #include <stdexcept>
  4. #include <string>
  5. namespace reginfo {
  6. // Minimal JSON object for flat string key/value pairs.
  7. // Supports only string values — sufficient for license data.
  8. class JsonObject {
  9. public:
  10. void set(const std::string& key, const std::string& value) { data_[key] = value; }
  11. std::string get(const std::string& key) const {
  12. auto it = data_.find(key);
  13. if (it == data_.end())
  14. throw std::runtime_error("Missing JSON key: " + key);
  15. return it->second;
  16. }
  17. std::string get(const std::string& key, const std::string& defaultValue) const {
  18. auto it = data_.find(key);
  19. return (it != data_.end()) ? it->second : defaultValue;
  20. }
  21. bool contains(const std::string& key) const {
  22. return data_.find(key) != data_.end();
  23. }
  24. // Parse from JSON string like {"key":"value",...}
  25. static JsonObject parse(const std::string& json);
  26. // Serialize to JSON string
  27. std::string dump(bool pretty = false) const;
  28. const std::map<std::string, std::string>& data() const { return data_; }
  29. private:
  30. std::map<std::string, std::string> data_;
  31. };
  32. } // namespace reginfo