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

使用nlohmann json为含嵌套Point的Rectangle实现to_json方法

嵌套结构体类型的to_json实现方案

你只需要给嵌套类型加上外层类的作用域限定符即可,完整实现如下(以常用的nlohmann/json库为例):

首先是结构体定义:

#include <nlohmann/json.hpp>
#include <string>
#include <array>

using json = nlohmann::json;

struct Rectangle
{
    struct Point
    {
        int x; int y;
    };
    std::string color;
    std::array<Point,4> points;
};

对应的to_json实现:

// 内嵌Point类型的序列化实现,注意参数类型要补全外层类作用域
void to_json(json& j, const Rectangle::Point& p) {
    j = json{{"x", p.x}, {"y", p.y}};
}

// Rectangle本身的序列化实现和之前写法完全一致
void to_json(json& j, const Rectangle& r) {
    j = json{{"color", r.color}, {"points", r.points}};
}

注意事项

  • 嵌套类仅作用域归属外层类,类型本身独立,只要写对完整类型名Rectangle::Point,参数依赖查找(ADL)就可以正常匹配到对应的序列化函数,使用逻辑和外部定义的Point完全一致。
  • 两个to_json函数必须和Rectangle结构体放在同一个命名空间下,如果你把Rectangle定义在自定义命名空间里,对应的to_json也要放在同一个命名空间内,示例如下:
namespace my_namespace {
struct Rectangle
{
    struct Point
    {
        int x; int y;
    };
    std::string color;
    std::array<Point,4> points;
};

void to_json(json& j, const Rectangle::Point& p) {
    j = json{{"x", p.x}, {"y", p.y}};
}

void to_json(json& j, const Rectangle& r) {
    j = json{{"color", r.color}, {"points", r.points}};
}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:09:02