使用nlohmann的json库序列化struct时出现问题

xoshrz7s  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(382)

我尝试用nlohmann的json库序列化这个结构体(该结构体在文件JsonResponsePacketSerializer.h中定义):

typedef struct GetRoomsResponse
{
    unsigned int status;
    std::vector<RoomData> rooms;
}GetRoomsResponse;

其中RoomData是在文件Room.h中定义的另一个结构体:

typedef struct RoomData
{
    unsigned int id;
    std::string name;
    unsigned int maxPlayers;
    unsigned int numOfQuestionsInGame;
    unsigned int timePerQuestion;
    unsigned int isActive;
}RoomData;

为了序列化这个结构体,我根据nlohmann的文档定义了这个user-macro:

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(GetRoomsResponse, status, rooms);

但是我假设这会导致许多错误,因为它不知道如何序列化结构体GetRoomsResponse中的结构体RoomData。
我试着给RoomData添加一个默认构造函数(尽管我很确定结构在默认情况下有一个默认构造函数),但它不起作用。

42fyovps

42fyovps1#

正如@AlanBirties的评论中提到的,结构体的所有组件都必须是可序列化的,结构体本身才能序列化(documentaiton)。
下面是一些示例代码,它也以标准的C++样式声明了结构。

示例代码

#include <iostream>
#include "nlohmann/json.hpp"

struct RoomData {
    unsigned int id;
    std::string name;
    unsigned int maxPlayers;
    unsigned int numOfQuestionsInGame;
    unsigned int timePerQuestion;
    unsigned int isActive;
};

struct GetRoomsResponse {
    unsigned int status;
    std::vector<RoomData> rooms;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(RoomData, id, name, maxPlayers, numOfQuestionsInGame, timePerQue\
stion, isActive);
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(GetRoomsResponse, status, rooms);

int main(int argc, const char *argv[]) {

    RoomData r0{1, "abc", 2, 3, 4, 5}, r1{6, "def", 7, 8, 9, 10};
    GetRoomsResponse resp{0, {r0, r1}};

    nlohmann::json j{resp};
    cout << j << endl;
    return 0;
}

输出

[{"rooms":[{"id":1,"isActive":5,"maxPlayers":2,"name":"abc","numOfQuestionsInGame":3,"timePerQue\
stion":4},{"id":6,"isActive":10,"maxPlayers":7,"name":"def","numOfQuestionsInGame":8,"timePerQue\
stion":9}],"status":0}]

相关问题