I created a struct:
{
unsigned int id;
std::string name;
unsigned int maxPlayers;
unsigned int numOfQuestionsInGame;
unsigned int timePerQuestion;
unsigned int isActive;
} RoomData;
In my code, I have to create a vector of RoomData and then convert it into a json object (I'm using nlohmann, and unable to use any other method due to restrictions in my instructions), and to do so, i tried to create a from_json and to_json functions.
The code itself (this is the header file of the code):
#include <iostream>
#include <string>
#include <vector>
#include "LoggedUser.h"
#include "json.hpp"
namespace nh = nlohmann;
namespace rd {
typedef struct RoomData
{
unsigned int id;
std::string name;
unsigned int maxPlayers;
unsigned int numOfQuestionsInGame;
unsigned int timePerQuestion;
unsigned int isActive;
} RoomData;
void from_json(const nh::json& j, RoomData& val)
{
j.at("id").get_to(val.id);
j.at("name").get_to(val.name);
j.at("maxPlayers").get_to(val.maxPlayers);
j.at("numOfQuestionsInGame").get_to(val.numOfQuestionsInGame);
j.at("timePerQuestion").get_to(val.timePerQuestion);
j.at("isActive").get_to(val.isActive);
}
void to_json(nh::json& j, const RoomData& val)
{
j["id"] = val.id;
j["name"] = val.name;
j["maxPlayers"] = val.maxPlayers;
j["numOfQuestionsInGame"] = val.numOfQuestionsInGame;
j["timePerQuestion"] = val.timePerQuestion;
j["isActive"] = val.isActive;
}
}
class Room
{
public:
Room() = default;
Room(const rd::RoomData& data);
void addUser(LoggedUser); // adds a user to the users vector
void removeUser(LoggedUser); // removes a user from the users vector
std::vector<std::string> getAllUsers(); // return a vector of all the users
// getters
rd::RoomData getRoomData() const;
private:
rd::RoomData m_metadata; // the data of the room
std::vector<LoggedUser> m_users; // the vector of the users in the room
};
After trying to run it, a LNK2005 error arises. I know that the type I use and those functions have to be in the same namespace, did I do it wrong?
The exact error:
"void cdecl to_json(class nlohmann::basic_json<class std::map,class std::vector,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool,int64,unsigned __int64,double,class std::allocator,struct nlohmann::adl_serializer,class std::vector<unsigned char,class std::allocator<unsigned char> > > &,struct RoomData const &)" (?to_json@@YAXAAV?$basic_json@Vmap@std@@Vvector@2@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@_N_J_KNVallocator@2@Uadl_serializer@nlohmann@@V?$vector@EV?$allocator@E@std@@@2@@nlohmann@@ABURoomData@@@Z) already defined in Communicator.obj