[Serialization] Make JsonSerializationContext FilesystemAppComponent-compatible

This commit is contained in:
SweetId 2024-03-11 19:08:10 -04:00
parent cc2c36c75d
commit 8cc1719d1b
2 changed files with 25 additions and 3 deletions

View File

@ -10,10 +10,13 @@ namespace Nz
: public SerializationContext : public SerializationContext
{ {
public: public:
struct Params {};
JsonSerializationContext(); JsonSerializationContext();
~JsonSerializationContext(); ~JsonSerializationContext();
bool Load(const std::filesystem::path& path); bool Load(const std::filesystem::path& path);
bool Load(Stream& stream);
EnumSerializationMode GetEnumSerializationMode() const override { return EnumSerializationMode::String; } EnumSerializationMode GetEnumSerializationMode() const override { return EnumSerializationMode::String; }
bool PushObject(std::string_view name) override; bool PushObject(std::string_view name) override;
@ -47,6 +50,8 @@ namespace Nz
bool Read(std::string_view name, double* value) override; bool Read(std::string_view name, double* value) override;
bool Read(std::string_view name, std::string* value) override; bool Read(std::string_view name, std::string* value) override;
static std::shared_ptr<JsonSerializationContext> LoadFromStream(Stream& stream, const Params& params = {});
private: private:
std::unique_ptr<struct JsonImpl> m_impl; std::unique_ptr<struct JsonImpl> m_impl;
}; };

View File

@ -36,11 +36,20 @@ namespace Nz
bool JsonSerializationContext::Load(const std::filesystem::path& path) bool JsonSerializationContext::Load(const std::filesystem::path& path)
{ {
std::ifstream file(path); Nz::File file(path, Nz::OpenMode::Read);
if (!file || !file.is_open()) return Load(file);
}
bool JsonSerializationContext::Load(Stream& stream)
{
if (!stream.IsReadable())
return false; return false;
m_impl->json = nlohmann::json::parse(file); auto size = stream.GetSize();
std::vector<char> content(size);
stream.Read(content.data(), content.size());
m_impl->json = nlohmann::json::parse(content.begin(), content.end());
m_impl->stack.push(&m_impl->json); m_impl->stack.push(&m_impl->json);
return true; return true;
} }
@ -129,4 +138,12 @@ namespace Nz
*value = m_impl->Top()[name].get<std::string>(); *value = m_impl->Top()[name].get<std::string>();
return true; return true;
} }
std::shared_ptr<JsonSerializationContext> JsonSerializationContext::LoadFromStream(Stream& stream, const JsonSerializationContext::Params&)
{
std::shared_ptr<JsonSerializationContext> context = std::make_shared<JsonSerializationContext>();
if (context->Load(stream))
return context;
return {};
}
} }