Skip to content

Commit 30bbabc

Browse files
committed
优化美化序列化算法
1 parent 85023b9 commit 30bbabc

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/jsonlib.cpp

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -643,40 +643,44 @@ namespace Jsonlib{
643643
{
644644
case JsonType::OBJECT:
645645
{
646-
std::string tabs(depth * space_num, ' ');
647646
// 对象类型
648647
std::string res{ "{" };
649-
648+
int tabs = depth * space_num + space_num;
650649
const auto& map = std::get<JsonObject>(content_);
651650
for (const auto& [fst, snd] : map) {
652-
res += '\n' + std::string(space_num, ' ') + tabs;
651+
res += '\n';
652+
res.append(tabs, ' ');
653653
// 键是字符串,需要反转义
654654
res += json_reverse_escape(fst);
655655
res += ": ";
656-
// 递归序列号
657656
res += snd.serialize_pretty(space_num, depth + 1);
658657
res += ',';
659658
}
660659
if (*res.rbegin() == ',') *res.rbegin() = '\n';
661-
if(!map.empty()) res += tabs + '}';
660+
if(!map.empty()){
661+
res.append(tabs - space_num, ' ');
662+
res += '}';
663+
}
662664
else res += " }";
663665
return res;
664666
}
665667
case JsonType::ARRAY:
666668
{
667-
std::string tabs(depth * space_num, ' ');
668669
// 数组类型
669670
std::string res{ "[" };
670-
671+
int tabs = depth * space_num + space_num;
671672
const auto& list = std::get<JsonArray>(content_);
672673
for (const JsonValue& it : list) {
673-
// 递归序列号
674-
res += '\n' + std::string(space_num, ' ') + tabs;
674+
res += '\n';
675+
res.append(tabs, ' ');
675676
res += it.serialize_pretty(space_num, depth + 1);
676677
res += ',';
677678
}
678679
if (*res.rbegin() == ',') *res.rbegin() = '\n';
679-
if(!list.empty()) res += tabs + ']';
680+
if(!list.empty()){
681+
res.append(tabs - space_num, ' ');
682+
res += ']';
683+
}
680684
else res += " ]";
681685
return res;
682686
}

0 commit comments

Comments
 (0)