-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJObject.cpp
More file actions
91 lines (87 loc) · 2.35 KB
/
Copy pathJObject.cpp
File metadata and controls
91 lines (87 loc) · 2.35 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "JObject.h"
using namespace json;
void *JObject::value()
{
// 判断jobject类下是否有m_type类型,返回对应类型值的地址
switch(m_type)
{
case T_NULL:
return get_if<str_t>(&m_value);
case T_BOOL:
return get_if<bool_t>(&m_value);
case T_INT:
return get_if<int_t>(&m_value);
case T_DOUBLE:
return get_if<double_t>(&m_value);
case T_LIST:
return get_if<list_t>(&m_value);
case T_DICT:
return get_if<dict_t>(&m_value);
case T_STR:
return std::get_if<str_t>(&m_value);
default:
return nullptr;
}
}
// 用于简化指针强转过程的宏
#define GET_VALUE(type) *((type *) value)
string JObject::to_string()
{
void *value = this->value();
// ostringstream的作用:
// 1. 字符串拼接
// 2. 数据转换为字符串
// 3. 构建格式化的字符串 .str()
std::ostringstream os;
switch(m_type)
{
case T_NULL:
os << "null";
break;
case T_BOOL:
if(GET_VALUE(bool))
os << "true";
else os << "false";
break;
case T_INT:
os << GET_VALUE(int);
break;
case T_DOUBLE:
os << GET_VALUE(double);
break;
case T_STR:
os << '\"' << GET_VALUE(string) << '\"';
break;
case T_LIST:
{
list_t &list = GET_VALUE(list_t);
os << '[';
for(auto i = 0; i < list.size(); i++)
{
if(i != list.size() - 1)
{
os << ((list[i]).to_string());
os << ',';
}else os << ((list[i]).to_string());
}
os << ']';
break;
}
case T_DICT:
{
dict_t &dict = GET_VALUE(dict_t);
os << '{';
for(auto it = dict.begin(); it != dict.end(); ++it)
{
if(it != dict.begin()) // 为了保证最后的json格式正确
os << ',';
os << '\"' << it->first << "\":" << it->second.to_string();
}
os << '}';
break;
}
default:
return "";
}
return os.str();
}