在c++中使用nlohmann从类到json的转换

conversion from class to json using nlohmann in c++

本文关键字:json 转换 nlohmann c++      更新时间:2023-10-16

我一直试图在visual studio 2017中将我的类转换为json,但存在链接器错误C2440。">

Severity    Code    Description Project File    Line    Suppression State
Error   C2440   'initializing': cannot convert from 'ns::person' to 'nlohmann::basic_json<std::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer>'   jason reader writer c:userslengdonsourcereposjason reader writerjason reader writerobjecttojason.h   15  

我的代码是:第1类:

#include<iostream>
#include<string>
#include"nlohmann/json.hpp"
#include"nlohmann/adl_serializer.hpp"
using namespace std;
using json = nlohmann::json;
namespace ns {
// a simple struct to model a person
class person {
public:
string name;
string address;
int age;
void to_json(json& j, const person& p) {
j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
}
void from_json(const json& j, person& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
};    
}

第2类:

#include"Student.h"
#include"nlohmann/json.hpp"
#include"nlohmann/adl_serializer.hpp"
using json = nlohmann::json;
using namespace std;
class ObjectToJason
{
public:
json convert()
{
ns::person p{ "Ned Flanders", "744 Evergreen Terrace", 60 };
json j=p;
}
};

在我为类2编写的代码中,json j=有错误">不存在合适的用户定义的从ns::person到json的转换"。我是c++和json的新手,所以请尝试用简单的英语解释。提前感谢

我想引用文档

https://github.com/nlohmann/json#arbitrary-类型转换

这些方法必须在类型的命名空间(可以是全局命名空间(中,否则库将无法定位它们(在本例中,它们位于命名空间ns中,其中定义了person(。

这意味着两个函数

void to_json(json& j, const person& p)
void from_json(const json& j, person& p)

应位于自定义对象所在的同一命名空间内。在你的情况下,这是一个普通人。

所以,你的第1类代码是:

#include<iostream>
#include<string>
#include"nlohmann/json.hpp"
#include"nlohmann/adl_serializer.hpp"
using namespace std;
using json = nlohmann::json;
namespace ns {
void to_json(json& j, const person& p) {
j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
}
void from_json(const json& j, person& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
// a simple struct to model a person
class person {
public:
string name;
string address;
int age;
};    
}

你的2级代码是:

#include"Student.h"
#include"nlohmann/json.hpp"
#include"nlohmann/adl_serializer.hpp"
using json = nlohmann::json;
using namespace std;
namespace ns {
class ObjectToJason
{
public:
json convert()
{
ns::person p{ "Ned Flanders", "744 Evergreen Terrace", 60 };
json j=p;
}
};
}

我希望这能有所帮助。

请在此处查看需求https://github.com/nlohmann/json#arbitrary-类型转换。将to_json和from_json移出类。