2024-06-05 19:04:53 -04:00
|
|
|
#ifndef RFL_JSON_READ_HPP_
|
|
|
|
#define RFL_JSON_READ_HPP_
|
|
|
|
|
|
|
|
#include <istream>
|
|
|
|
#include <string>
|
2024-06-08 14:10:59 -04:00
|
|
|
#include <yyjson.h>
|
2024-06-05 19:04:53 -04:00
|
|
|
|
|
|
|
#include "../Processors.hpp"
|
|
|
|
#include "../internal/wrap_in_rfl_array_t.hpp"
|
|
|
|
#include "Parser.hpp"
|
|
|
|
#include "Reader.hpp"
|
|
|
|
|
|
|
|
namespace rfl {
|
2024-06-08 14:10:59 -04:00
|
|
|
namespace json {
|
|
|
|
|
|
|
|
using InputObjectType = typename Reader::InputObjectType;
|
|
|
|
using InputVarType = typename Reader::InputVarType;
|
|
|
|
|
|
|
|
/// Parses an object from a JSON var.
|
|
|
|
template <class T, class... Ps>
|
|
|
|
auto read(const InputVarType& _obj) {
|
|
|
|
const auto r = Reader();
|
|
|
|
return Parser<T, Processors<Ps...>>::read(r, _obj);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses an object from JSON using reflection.
|
|
|
|
template <class T, class... Ps>
|
2024-06-08 15:53:06 -04:00
|
|
|
Result<internal::wrap_in_rfl_array_t<T>> read(const std::string& _json_str
|
|
|
|
) {
|
2024-06-08 14:10:59 -04:00
|
|
|
yyjson_doc* doc = yyjson_read(_json_str.c_str(), _json_str.size(), 0);
|
|
|
|
if (!doc) { return Error("Could not parse document"); }
|
|
|
|
yyjson_val* root = yyjson_doc_get_root(doc);
|
2024-06-08 15:53:06 -04:00
|
|
|
const auto r = Reader();
|
2024-06-08 14:10:59 -04:00
|
|
|
auto res = Parser<T, Processors<Ps...>>::read(r, InputVarType(root));
|
|
|
|
yyjson_doc_free(doc);
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses an object from a stringstream.
|
|
|
|
template <class T, class... Ps>
|
|
|
|
auto read(std::istream& _stream) {
|
2024-06-08 15:53:06 -04:00
|
|
|
const auto json_str = std::string(
|
|
|
|
std::istreambuf_iterator<char>(_stream),
|
|
|
|
std::istreambuf_iterator<char>()
|
|
|
|
);
|
2024-06-08 14:10:59 -04:00
|
|
|
return read<T, Ps...>(json_str);
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace json
|
|
|
|
} // namespace rfl
|
2024-06-05 19:04:53 -04:00
|
|
|
|
|
|
|
#endif
|