代码

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
// 解析JSON
void TestBoostJson()
{
std::cout << "TestBoostJson" << "\n";
// serialize
boost::json::object org;
org["name"] = "你好啊\\ AA BB CC 联通 鸡蛋灌饼 !()";
std::cout << "name:\t"<<org["name"] << "\n";
auto szJson = boost::json::serialize(org);
std::cout << "json:\t" << szJson << "\n";
// parse
boost::json::error_code ec;
boost::json::parse_options opt;
opt.allow_comments = true;
opt.allow_trailing_commas = true;
opt.allow_invalid_utf8 = true;
auto obj = boost::json::parse(szJson, {}, opt);
std::string name = obj.as_object()["name"].as_string().c_str();
std::cout << "name:\t" << name << "\n";
return;
}
// 解析UTF8的JSON
void TestBoostJsonUTF8()
{
std::cout << "TestBoostJsonUTF8" << "\n";
auto name = "你好啊\\ AA BB CC 联通 鸡蛋灌饼 !()";
std::cout << "name:\t" << name << "\n";
// utf8
auto utf8 = boost::locale::conv::between(name, "UTF-8", "GBK");
std::cout << "utf8 name:\t" << utf8 << "\n";
// serialize
boost::json::object utf8Ojb;
utf8Ojb["name"] = utf8;
auto szJson = boost::json::serialize(utf8Ojb);
std::cout << "utf8 json:\t" << szJson << "\n";
// parse
boost::json::error_code ec;
boost::json::parse_options opt;
opt.allow_comments = true;
opt.allow_trailing_commas = true;
opt.allow_invalid_utf8 = true;
auto obj = boost::json::parse(szJson, {}, opt);
name = obj.as_object()["name"].as_string().c_str();
std::cout << "utf8 name:\t" << name << "\n";
auto gbk = boost::locale::conv::between(name, "GBK", "UTF-8");
std::cout << "gbk name:\t" << gbk << "\n";
return;
}


int main(int argc, char** argv)
{
TestBoostJson();
TestBoostJsonUTF8();
return 0;
}

输出

在这里插入图片描述