将可变参数模板参数转换为 JSON 字符串
Convert variadic template arguments to JSON string
我需要一个接收可变参数模板参数并返回 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";
}
谢谢大家!
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 在c++中使用nlohmann从类到json的转换
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 将可变参数模板参数转换为 JSON 字符串
- C++-JSON::值用作函数参数中的重新引用
- 将 JSON 对象作为参数在 JNI 中传递给 CPP,并在 CPP 中检索 JSON 对象的数据
- 休息:当我尝试制作包含JSON参数的requst时发出问题
- HTTP_POST请求中ESP8266 JSON 参数