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

CppRestSdk自定义JSON反序列化如何支持std::vector数组类型解析

CppRestSdk 序列化方案适配std::vector的实现

现有代码修正

你现有代码存在三处需要先修复的问题:

  • Dog结构体的properties元组定义中,多个property项之间缺少逗号分隔
  • 所有property的name参数是宽字符类型,需要给字符串字面量添加L前缀,比如L"barkType"
  • fromJson函数内调用asAny时参数错误,应该传入data.at(property.name)而非字段名本身,修正后的对应代码段为:
if (data.has_field(property.name))
{
    object.*(property.member) = asAny<Type>(data.at(property.name));
}

新增vector类型适配逻辑

只需要添加asAny针对std::vector的偏特化实现,即可自动适配所有数组类型的解析:

template<typename T>
std::vector<T> asAny<std::vector<T>>(const web::json::value& value)
{
    std::vector<T> res;
    if (value.is_null() || !value.is_array()) {
        return res;
    }
    const auto& json_arr = value.as_array();
    res.reserve(json_arr.size());
    for (const auto& elem : json_arr) {
        res.push_back(asAny<T>(elem));
    }
    return res;
}

补充其他必要特化与定义

由于你定义的Owl、Cat结构体使用了std::string类型,需要补充对应的特化和结构体反射定义:

  1. 补充std::string的asAny特化:
template<>
std::string asAny<std::string>(const web::json::value& value)
{
    if (value.is_null()) {
        return "";
    }
    return utility::conversions::to_utf8string(value.as_string());
}
  1. 给Owl、Cat添加properties反射定义:
struct Owl
{
  std::string name;
  constexpr static auto properties = std::make_tuple(
      property(&Owl::name, L"name")
  );
};
struct Cat
{
  std::string name;
  int age;
  constexpr static auto properties = std::make_tuple(
      property(&Cat::name, L"name"),
      property(&Cat::age, L"age")
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 05:45:05