2019-12-06 11:40:23 +03:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <winrt/Windows.Foundation.h>
|
2020-04-29 13:02:18 -07:00
|
|
|
#include <winrt/Windows.Foundation.Collections.h>
|
2019-12-06 11:40:23 +03:00
|
|
|
#include <winrt/Windows.Data.Json.h>
|
|
|
|
|
|
|
|
#include <optional>
|
2020-12-15 15:16:09 +03:00
|
|
|
#include <fstream>
|
2019-12-06 11:40:23 +03:00
|
|
|
|
|
|
|
namespace json
|
|
|
|
{
|
2020-03-05 13:07:06 +03:00
|
|
|
using namespace winrt::Windows::Data::Json;
|
|
|
|
|
2020-12-15 15:16:09 +03:00
|
|
|
inline std::optional<JsonObject> from_file(std::wstring_view file_name)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
std::ifstream file(file_name.data(), std::ios::binary);
|
|
|
|
if (file.is_open())
|
|
|
|
{
|
|
|
|
using isbi = std::istreambuf_iterator<char>;
|
|
|
|
std::string obj_str{ isbi{ file }, isbi{} };
|
|
|
|
return JsonValue::Parse(winrt::to_hstring(obj_str)).GetObjectW();
|
|
|
|
}
|
|
|
|
return std::nullopt;
|
|
|
|
}
|
|
|
|
catch (...)
|
|
|
|
{
|
|
|
|
return std::nullopt;
|
|
|
|
}
|
|
|
|
}
|
2020-03-05 13:07:06 +03:00
|
|
|
|
2020-12-15 15:16:09 +03:00
|
|
|
inline void to_file(std::wstring_view file_name, const JsonObject& obj)
|
|
|
|
{
|
|
|
|
std::wstring obj_str{ obj.Stringify().c_str() };
|
|
|
|
std::ofstream{ file_name.data(), std::ios::binary } << winrt::to_string(obj_str);
|
|
|
|
}
|
2020-03-05 13:07:06 +03:00
|
|
|
|
|
|
|
inline bool has(
|
|
|
|
const json::JsonObject& o,
|
|
|
|
std::wstring_view name,
|
|
|
|
const json::JsonValueType type = JsonValueType::Object)
|
|
|
|
{
|
|
|
|
return o.HasKey(name) && o.GetNamedValue(name).ValueType() == type;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
inline std::enable_if_t<std::is_arithmetic_v<T>, JsonValue> value(const T arithmetic)
|
|
|
|
{
|
|
|
|
return json::JsonValue::CreateNumberValue(arithmetic);
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
inline std::enable_if_t<!std::is_arithmetic_v<T>, JsonValue> value(T s)
|
|
|
|
{
|
|
|
|
return json::JsonValue::CreateStringValue(s);
|
|
|
|
}
|
|
|
|
|
|
|
|
inline JsonValue value(const bool boolean)
|
|
|
|
{
|
|
|
|
return json::JsonValue::CreateBooleanValue(boolean);
|
|
|
|
}
|
|
|
|
|
|
|
|
inline JsonValue value(JsonObject value)
|
|
|
|
{
|
|
|
|
return value.as<JsonValue>();
|
|
|
|
}
|
|
|
|
|
|
|
|
inline JsonValue value(JsonValue value)
|
|
|
|
{
|
|
|
|
return value; // identity function overload for convenience
|
|
|
|
}
|
2019-12-06 11:40:23 +03:00
|
|
|
}
|