我有一个类,它需要一个nlohmann::json
对象作为它的第一个构造函数参数。我已经为我的类实现了to_json
和from_json
,但是from_json
不会被调用(除非我显式地调用它),并且默认的非结构化只是将整个对象放入json
参数中。下面是一些示例代码。
#include <iostream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
class ExampleClass
{
public:
ExampleClass(json data = json::object(), std::string some_string = "") : m_Data(data), m_String(some_string) {}
~ExampleClass() {}
json m_Data;
std::string m_String;
};
void to_json(json& j, const ExampleClass& example)
{
j = json{ {"Data", example.m_Data}, {"String", example.m_String} };
}
void from_json(const json& j, ExampleClass& example)
{
j.at("Data").get_to(example.m_Data);
j.at("String").get_to(example.m_String);
}
int main()
{
ExampleClass example(json{ {"key", "value"} }, "here's a string");
std::cout << json(example) << std::endl; // {"Data":{"key":"value"},"String":"here's a string"}
ExampleClass example_two = json::parse("{\"Data\":{\"key\":\"value\"},\"String\":\"here's a string\"}");
std::cout << json(example_two) << std::endl; // {"Data":{"Data":{"key":"value"},"String":"here's a string"},"String":""}
ExampleClass example_three;
from_json(json::parse("{\"Data\":{\"key\":\"value\"},\"String\":\"here's a string\"}"), example_three);
std::cout << json(example_three) << std::endl; // {"Data":{"key":"value"},"String":"here's a string"}
}
字符串
正如你所看到的,显式调用我写的from_json
方法可以正常工作,但我已经读到你不应该这样做。我在项目中的其他地方对几十个类使用了这种模式,只有需要json
对象作为第一个(或唯一的)构造函数参数的类遇到了这个问题。把一个非json参数放在第一个会让一切正常工作,但我不明白我做错了什么这对我不起作用
1条答案
按热度按时间tv6aics11#
问题是你实际上并不想在
example_two
的情况下调用构造函数。因此,你应该让你的构造函数explicit
来避免意外调用。字符串
演示:https://godbolt.org/z/Tr1YxTa5j