You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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_json function is a special overload that the nlohmann/json library looks for when converting custom types to JSON. It maps each member variable of RoomData to a corresponding key-value pair in a JSON object.
  • When you create a json instance from your vector<RoomData>, the library automatically uses your to_json function to serialize each RoomData element into a JSON object, then aggregates all those objects into a JSON array.

Quick tips:

  • If your RoomData class is in a namespace, place the to_json function in the same namespace (this leverages C++ argument-dependent lookup to ensure the library finds it).
  • For efficiency, consider passing the vector<RoomData> to your serialize function as a const std::vector<RoomData>& (const reference) instead of by value.
  • If you need to deserialize JSON back into RoomData objects later, you’ll need a corresponding from_json function overload that reverses the mapping.

内容的提问来源于stack exchange,提问作者Osher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:13:38