使用nlohmann/json.hpp序列化RoomData向量为JSON数组报错求助
Fixing RoomData Serialization with nlohmann/json
The error you’re encountering occurs because the nlohmann/json library doesn’t have built-in logic to serialize your custom RoomData class. To resolve this, you need to explicitly tell the library how to convert a RoomData object into a JSON structure by adding a to_json function overload.
Here’s the corrected code:
#include <string> #include <vector> #include <nlohmann/json.hpp> using nlohmann::json; class RoomData { public: int id; std::string name; int maxPlayers; int timePerQuestion; int isActive; }; // Add this function to define serialization for RoomData void to_json(json& j, const RoomData& room) { j = json{ {"id", room.id}, {"name", room.name}, {"maxPlayers", room.maxPlayers}, {"timePerQuestion", room.timePerQuestion}, {"isActive", room.isActive} }; } // Your serialize function works once the to_json overload exists std::string serialize(std::vector<RoomData> roomData) { json j(roomData); return j.dump(); }
Why this fixes the issue:
- The
to_jsonfunction is a special overload that the nlohmann/json library looks for when converting custom types to JSON. It maps each member variable ofRoomDatato a corresponding key-value pair in a JSON object. - When you create a
jsoninstance from yourvector<RoomData>, the library automatically uses yourto_jsonfunction to serialize eachRoomDataelement into a JSON object, then aggregates all those objects into a JSON array.
Quick tips:
- If your
RoomDataclass is in a namespace, place theto_jsonfunction in the same namespace (this leverages C++ argument-dependent lookup to ensure the library finds it). - For efficiency, consider passing the
vector<RoomData>to yourserializefunction as aconst std::vector<RoomData>&(const reference) instead of by value. - If you need to deserialize JSON back into
RoomDataobjects later, you’ll need a correspondingfrom_jsonfunction overload that reverses the mapping.
内容的提问来源于stack exchange,提问作者Osher
相关产品推荐
相关产品推荐

