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类型,需要补充对应的特化和结构体反射定义:
- 补充
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()); }
- 给
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
相关产品推荐
相关产品推荐

