Skip to content
Repos

DevPlaceApp

C++ 1.2 KB33 lines Opens in site

Directory Raw Download

#include "core/JsonDecode.hpp"

namespace dp {

const Json& JsonDecode::object(const Json& j, const char* what) {
  if (!j.is_object()) throw DecodeError(std::string("expected object: ") + what);
  return j;
}

const Json& JsonDecode::child(const Json& j, const char* key) {
  if (!j.is_object()) throw DecodeError("expected object");
  auto it = j.find(key);
  if (it == j.end() || it->is_null()) throw DecodeError(std::string("missing key: ") + key);
  return *it;
}

Date JsonDecode::toDate(const Json& value, const char* key) {
  if (!value.is_string()) throw DecodeError(std::string("date is not a string: ") + key);
  auto parsed = DateCodec::parseIso8601(value.get<std::string>());
  if (!parsed) throw DecodeError(std::string("Could not decode date from ") + value.get<std::string>() + ".");
  return *parsed;
}

Date JsonDecode::reqDate(const Json& j, const char* key) { return toDate(child(j, key), key); }

std::optional<Date> JsonDecode::optDate(const Json& j, const char* key) {
  if (!j.is_object()) throw DecodeError("expected object");
  auto it = j.find(key);
  if (it == j.end() || it->is_null()) return std::nullopt;
  return toDate(*it, key);
}

}  // namespace dp
18.6ms