forked from keizi666/charu3
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonHelper.cpp
73 lines (66 loc) · 2.15 KB
/
jsonHelper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "stdafx.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include <vector>
#include "nlomann/json.hpp"
#include "jsonHelper.h"
bool jsonHelper::GetBoolProperty(nlohmann::json& j, const char* key, bool defaultValue)
{
nlohmann::json::iterator it = j.find(key);
return (it != j.end() && it.value().is_boolean()) ? it.value().get<bool>() : defaultValue;
}
double jsonHelper::GetNumberProperty(nlohmann::json& j, const char* key, double defaultValue)
{
nlohmann::json::iterator it = j.find(key);
return (it != j.end() && it.value().is_number()) ? it.value().get<double>() : defaultValue;
}
std::string jsonHelper::GetStringProperty(nlohmann::json& j, const char* key, std::string defaultValue)
{
nlohmann::json::iterator it = j.find(key);
return (it != j.end() && it.value().is_string()) ? it.value().get<std::string>() : defaultValue;
}
CString jsonHelper::GetStringPropertyAsCString(nlohmann::json& j, const char* key, CString defaultValue)
{
nlohmann::json::iterator it = j.find(key);
if (it == j.end()) {
return defaultValue;
}
CString cs;
if (!GetCString(it.value(), cs)) {
return defaultValue;
}
return cs;
}
bool jsonHelper::GetCString(nlohmann::json j, CString& cs)
{
if (!j.is_string()) {
return false;
}
std::string s = j.get<std::string>();
const char* cptr = s.c_str();
int size = MultiByteToWideChar(CP_UTF8, 0, cptr, -1, nullptr, 0);
wchar_t* wbuf = new wchar_t[size];
if (!wbuf) {
return false;
}
MultiByteToWideChar(CP_UTF8, 0, cptr, -1, wbuf, size);
cs = CString(wbuf);
delete[] wbuf;
return true;
}
void jsonHelper::AppendCStringArray(nlohmann::json& j, const char* key, std::vector<CString>& list)
{
nlohmann::json::iterator it = j.find(key);
if (it != j.end() && it.value().is_array()) {
nlohmann::json array = it.value();
for (nlohmann::json& item : array) {
CString cs;
if (GetCString(item, cs)) {
list.push_back(cs);
}
}
}
}