I need a function that receives variadic template arguments and returns a JSON array string.
I was able to reach this point:
#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";
}
But it did not work for booleans and null.
As you can notice, I am not a C++ developer.
If you know another method, you can share it too.