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