Files
dl_old/dl/io/dl_json.cpp
T
2026-07-31 18:57:15 +08:00

74 lines
1.2 KiB
C++

#include "io/dl_json.h"
#include "io/dl_file.h"
#include "io/dl_log.h"
#include "base/dl_string.h"
namespace dl::Json
{
bool g_bJsonLog = true;
void SetLog(bool open)
{
g_bJsonLog = open;
}
json Parse(BufferView buf, bool binary)
{
// 基础接口
try
{
json j;
if (binary)
{
j = json::from_cbor(buf.data(), buf.data() + buf.size());
}
else
{
j = json::parse((char*)buf.data(), (char*)buf.data() + buf.size());
}
return j;
}
catch (nlohmann::detail::exception& e)
{
if (g_bJsonLog)
log_err("解析失败:{}", dl::to_string(e));
}
return {};
}
json ParseString(std::string_view str)
{
return Parse(CreateBufferView(str));
}
json ParseFile(std::string_view path_name, bool binary)
{
if (!File::IsExist(path_name))
{
if (g_bJsonLog)
log_warn("文件不存在:{}", path_name);
return {};
}
if (binary)
{
Buffer buf = File::GetBuffer(path_name);
return Parse(buf, binary);
}
else
{
std::string str = File::GetString(path_name);
return ParseString(str);
}
}
bool SaveFile(const json& j, std::string_view path_name, bool binary /*= false*/)
{
if (binary)
return File::SaveBuffer(CreateBufferView(json::to_cbor(j)), path_name);
else
return File::SaveString(j.dump(4), path_name);
}
}