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
45
50json ParseFile(std::string_view path_name);
51
56inline json ParseString(std::string_view str)
57{
58 return Parse(CreateBufferView(str));
59}
60
61
65template<typename T>
66bool Get(const json& j, const std::string& name, T& t)
67{
68 auto iter = j.find(name);
69 if (iter == j.end())
70 {
71 if(g_bJsonLog)
72 log_err("json取值失败:{}", name);
73 return false;
74 }
75 try
76 {
77 t = *iter;
78 return true;
79 }
80 catch (nlohmann::detail::exception& e)
81 {
82 // 存在但失败,必须报错
83 log_err("json取值失败({}): {}", name, e.what());
84 }
85 return false;
86}
87
90template<typename T>
91bool Get(const json& j, T& t)
92{
93 try
94 {
95 t = j;
96 return true;
97 }
98 catch (nlohmann::detail::exception& e)
99 {
100 // 存在但失败,必须报错
101 log_err("json取值失败: {}", e.what());
102 }
103 return false;
104}
105
109inline std::string Dump(json& j)
110{
111 j.dump(4, ' ', false, nlohmann::json::error_handler_t::replace);
112
113 return j.dump(4);
114}
115
118inline std::string Dump(BufferView buf)
119{
120 json j = Parse(buf);
121 if (j.is_null())
122 return {};
123 return Dump(j);
124}
125}
126
127namespace dl
128{
129 template<typename T, size_t N>
130 void from_json(const json& j, Array<T, N>& arr)
131 {
132 for (size_t i = 0; i < N; ++i)
133 {
134 arr[i] = j.at(i).get<T>();
135 }
136 }
137
138 template<typename T, size_t N>
139 void to_json(json& j, const Array<T, N>& arr)
140 {
141 j = json::array();
142 for (size_t i = 0; i < N; ++i)
143 {
144 j.push_back(arr[i]);
145 }
146 }
147}
constexpr T & at(size_t i)
类似std::array,增加xyzw、wh等成员访问
表示一段内存
nlohmann::json json
日志系统
#define log_err(...)
json格式
void SetLog(bool open)
设置是否提示输出日志(请直接使用DisableLog来关闭后,自动恢复)
json ParseString(std::string_view str)
从 字符串 构建json对象
bool g_bJsonLog
json ParseFile(std::string_view path_name)
从 文件 构建json对象
json Parse(BufferView buf)
从 内存 构建json对象
bool Get(const json &j, const std::string &name, T &t)
从json返回值,不存在则返回false,打印日志
std::string Dump(json &j)
dump
std::span< std::byte > BufferView
void from_json(const json &j, Array< T, N > &arr)
BufferView CreateBufferView(std::string_view str)
创建buffer视图
void to_json(json &j, const Array< T, N > &arr)