将可变参数模板参数转换为 JSON 字符串

Convert variadic template arguments to JSON string

本文关键字:参数 JSON 字符串 转换 变参      更新时间:2023-10-16

我需要一个接收可变参数模板参数并返回 JSON 数组字符串的函数。

我能够达到这一点:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
template<typename Arg>
void add_value(std::stringstream &result, Arg arg){
if (result.rdbuf()->in_avail())
result << ",";
if (std::is_same_v<Arg, string>) {
result << """ << arg << """;
} else if (std::is_same_v<Arg, const char*>) {
result << """ << arg << """;
} else if (std::is_same_v<Arg, char*>) {
result << """ << arg << """;
} else if (std::is_same_v<Arg, bool>) {
result << arg;
} else {
result << arg;
}
}
template<typename... Args>
std::string to_json_array(Args... args) {
std::stringstream result;
(add_value(result, args), ...);
return "[" + result.str() + "]";
}
int main() {
std::string result;
char aa[10] = "haha";
char *bb = aa;
result = to_json_array(123, "Hello", 1.5, string("World!"), true, aa, false, bb, NULL);
std::cout << result << "n";
}

但它不适用于布尔值和空值。

正如你所注意到的,我不是一个C++开发人员。

如果您知道另一种方法,也可以分享。

我在评论的帮助下分享我得到的解决方案:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
template<typename Arg>
void add_value(std::stringstream &result, Arg arg){
if (result.rdbuf()->in_avail())
result << ",";
if constexpr (std::is_same_v<Arg, string>) {
result << """ << arg << """;
} else if constexpr (std::is_same_v<Arg, const char*>) {
result << """ << arg << """;
} else if constexpr (std::is_same_v<Arg, char*>) {
result << """ << arg << """;
} else if constexpr (std::is_same_v<Arg, bool>) {
result << std::boolalpha;
result << arg;
result << std::noboolalpha;
} else if constexpr (std::is_same_v<Arg, nullptr_t>) {
result << "null";
} else {
result << arg;
}
}
template<typename... Args>
std::string to_json_array(Args... args) {
std::stringstream result;
(add_value(result, args), ...);
return "[" + result.str() + "]";
}
int main() {
std::string result;
char aa[10] = "haha";
char *bb = aa;
result = to_json_array(123, "Hello", 1.5, string("World!"), true, aa, false, bb, nullptr, 0);
std::cout << result << "n";
}

谢谢大家!