无法使用带有私有成员的自定义 class 使用 nlohmann json 从 Json 反序列化

Can't deserialise from Json using nlohman json using custom class with private members

真的很难做到这一点;它应该很简单,但我不知道怎么做。它适用于结构,但不适用于具有私有成员的 class。按照 (https://github.com/nlohmann/json) 的说明进行操作。我在 Visual Studio 2019 年构建它并从 nuget 版本 3.10.4.

获得了库

错误出现在 main.cpp 中的 get 行上,其中显示“未找到匹配的重载函数调用”。列出了另外两个错误;

Error (active) E0304 no instance of overloaded function "nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType>::get [with ObjectType=std::map, ArrayType=std::vector, StringType=std::string, BooleanType=bool, NumberIntegerType=int64_t, NumberUnsignedType=uint64_t, NumberFloatType=double, AllocatorType=std::allocator, JSONSerializer=nlohmann::adl_serializer, BinaryType=std::vector<uint8_t, std::allocator<uint8_t>>]" matches the argument list Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120
object type is: json

Error C2672 'nlohmann::basic_jsonstd::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>::get': no matching overloaded function found Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120

Error C2893 Failed to specialize function template 'unknown-type nlohmann::basic_jsonstd::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>::get(void) noexcept() const' Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120

这是我的 address1.h

#include <nlohmann/json.hpp>
#include <string>

using json = nlohmann::json;

class address1 {
private:
    std::string street;
    int housenumber;
    int postcode;

public:
    address1(std::string street, int housenumber, int postcode);
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(address1, street, housenumber, postcode);
};

address1.cpp

#include "address1.h"

address1::address1(std::string street, int housenumber, int postcode) :street(street), housenumber(housenumber), postcode(postcode) {}

main.cpp

int main(int argc, const char** argv) {
    address1 p1 = { "home",2,3 };
    json j = p1;
    auto p3 = j.get<address1>();
    std::cout << std::setw(2) << j << std::endl;
}

问题是您的 address1 类型没有默认构造函数。来自 https://nlohmann.github.io/json/features/arbitrary_types/#basic-usage :

When using get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)

如果我将 address1() = default; 添加到您的示例中,则编译没有问题。

Ps。 “稍后描述的旁路”可以在这里找到:https://nlohmann.github.io/json/features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types