dl
dl_json.h
浏览该文件的文档.
1
12#pragma once
13
14#include <json.hpp>
15
16#include "io/dl_log.h"
17#include "base/dl_array.h"
18#include "memory/dl_buffer.h"
19
20using json = nlohmann::json;
21
23namespace dl::Json
24{
25
26 extern bool g_bJsonLog;
27
31void SetLog(bool open);
32
35{
36 DisableLog() { SetLog(false); }
37 ~DisableLog() { SetLog(true); }
38};
39
46json Parse(BufferView buf, bool binary = false);
47
54json ParseFile(std::string_view path_name, bool binary = false);
55
61json ParseString(std::string_view str);
62
63
67template<typename T>
68bool Get(const json& j, const std::string& name, T& t)
69{
70 auto iter = j.find(name);
71 if (iter == j.end())
72 {
73 if(g_bJsonLog)
74 log_err("json取值失败:{}", name);
75 return false;
76 }
77 try
78 {
79 t = iter->get<T>();
80 return true;
81 }
82 catch (nlohmann::detail::exception& e)
83 {
84 // 存在但失败,必须报错
85 log_err("json取值失败({}): {}", name, e.what());
86 }
87 return false;
88}
89
92template<typename T>
93bool Cast(const json& j, T& t)
94{
95 try
96 {
97 t = j;
98 return true;
99 }
100 catch (nlohmann::detail::exception& e)
101 {
102 // 存在但失败,必须报错
103 log_err("json取值失败: {}", e.what());
104 }
105 return false;
106}
107
111inline std::string Dump(json& j)
112{
113 j.dump(4, ' ', false, nlohmann::json::error_handler_t::replace);
114
115 return j.dump(4);
116}
117
120inline std::string Dump(BufferView buf)
121{
122 json j = Parse(buf);
123 if (j.is_null())
124 return {};
125 return Dump(j);
126}
127
132bool SaveFile(const json& j, std::string_view path_name, bool binary = false);
133
134}
135
136namespace dl
137{
138 template<typename T, size_t N>
139 void from_json(const json& j, Array<T, N>& arr)
140 {
141 for (size_t i = 0; i < N; ++i)
142 {
143 arr[i] = j.at(i).get<T>();
144 }
145 }
146
147 template<typename T, size_t N>
148 void to_json(json& j, const Array<T, N>& arr)
149 {
150 j = json::array();
151 for (size_t i = 0; i < N; ++i)
152 {
153 j.push_back(arr[i]);
154 }
155 }
156}
constexpr T & at(size_t i)
类似std::array,增加xyzw、wh等成员访问
表示一段内存
nlohmann::json json
日志系统
#define log_err(...)
json格式
void SetLog(bool open)
设置是否提示输出日志(请直接使用DisableLog来关闭后,自动恢复)
bool Cast(const json &j, T &t)
从json返回值,不存在则返回false,打印日志
json Parse(BufferView buf, bool binary=false)
从 内存 构建json对象
json ParseString(std::string_view str)
从 字符串 构建json对象
bool g_bJsonLog
bool Get(const json &j, const std::string &name, T &t)
从json返回子元素值,不存在则返回false,打印日志
json ParseFile(std::string_view path_name, bool binary=false)
从 文件 构建json对象
std::string Dump(json &j)
dump
bool SaveFile(const json &j, std::string_view path_name, bool binary=false)
保存到文件
void from_json(const json &j, Array< T, N > &arr)
void to_json(json &j, const Array< T, N > &arr)