我有下面的代码,它可以很好地使用包含int和std::string类型的基本结构。我已经做了一个自定义助手来将原始json转换为我的结构类型。
#include <iomanip>
#include <iostream>
#include <nlohmann/json.hpp>
struct test {
int num;
std::string value_one;
std::string value_two;
std::string value_three;
};
void from_json(const nlohmann::json& j, test& p) {
j.at("amount").get_to(p.num);
j.at("value1").get_to(p.value_one);
j.at("value2").get_to(p.value_two);
j.at("value3").get_to(p.value_three);
}
// cppcheck-suppress unusedFunction
auto check(test& response_body, const std::string& resp) -> bool {
nlohmann::json payment_body{};
{
nlohmann::json j1 = nlohmann::json::parse(resp);
payment_body = j1;
}
std::cout << std::setw(4) << payment_body << "\n";
response_body = payment_body.get<test>();
return true;
}
int main(int argc, char** argv) {
std::string json_value = R"({
"amount" : 1500,
"value1" : "yes",
"value2" : "no",
"value3" : "maybe"
}
)";
test resp{};
check(resp, json_value);
std::cout << resp.num << "\t" << resp.value_one << "\t "<<
resp.value_two << "\t"<< resp.value_three << "\n";
return 0;
}
字符串
我遇到的问题是,我的代码需要std::string
类型为char *
,因为此代码位于dll中,并且结构是从使用不同编译器构建的应用程序传递的。实际上,此结构要大得多,但我在from_json
中可能会看到类似的东西
std::string name = j.at("value1").get<std::string>();
p.value_one= new char[name.length() + 1];
std::strcpy(p.value_one, name.c_str());
型
他们是否有一种替代的更清洁的方法可以在这里采用
1条答案
按热度按时间8nuwlpux1#
我遇到的问题是,我的代码需要
std::string
类型是char *
.因此,如果您的
struct
看起来像这样,字符串
然后在
from_json
中使用它型