c++ - 如何在 C++ 中表示 JSON 文档的递归对象结构?
问题描述
我想表示一个类似 json 的文件,如下所示...
{
root_att_0: 23,
root_att_1:
{
root_att_1_att_0: "Peter",
root_att_1_att_1: 3.14f
},
root_att_2: ["Hello", "World"],
root_att_3:
{
root_att_3_att_0: 64,
root_att_3_att_1:
{
root_att_3_att_1_att_0: 123
}
},
root_att_4: true
}
在 C++ 中使用树结构,如下图所示...
我试图用下面的代码来实现那个表示......
using JSONType = std::variant
<
bool,
int,
float,
double,
std::string,
std::vector<bool>,
std::vector<int>,
std::vector<float>,
std::vector<double>,
std::vector<std::string>
>;
struct JSONObject
{
std::unordered_map<std::string, std::variant<JSONType, JSONObject>> attributes;
};
int main()
{
JSONObject o
{
{"string", std::variant<JSONType, JSONObject>(JSONType(true))}
};
}
但是在使用 unordered_map 条目初始化 JSONObject o 时,我总是收到以下错误。我不明白为什么我在初始化中给出的值是错误的......
no instance of constructor "std::unordered_map<_Kty, _Ty, _Hasher,
_Keyeq, _Alloc>::unordered_map [with _Kty=std::string,
_Ty=std::variant<JSONType, JSONObject>,
_Hasher=std::hash<std::string>, _Keyeq=std::equal_to<std::string>,
_Alloc=std::allocator<std::pair<const std::string,
std::variant<JSONType, JSONObject>>>]" matches the argument list
argument types are: (const char [7], std::variant<JSONType, JSONObject>)
解决方案
JSONObject o
{
{"string", std::variant<JSONType, JSONObject>(JSONType(true))}
};
缺少一组大括号。您需要一组用于JSONObject
,一组用于attributes
成员,最后一组用于映射条目:
JSONObject o
{
{
{"string", std::variant<JSONType, JSONObject>(JSONType(true))}
}
};
推荐阅读
- nginx - 如何为除某些端点之外的所有端点提供 404 响应
- pine-script - 如何修复“无法使用参数调用 rma”错误?
- wordpress - 线夹和 Wordpress 的问题
- amazon-web-services - 如何使用 React Native 安全访问 AWS Cloudfront 中的内容
- c# - 如何验证已在 Selenium 中调用了 DOM 事件
- oracle - 如何使用 PL/SQL (Oracle 10g) 从另一个 PL/SQL 文件的包函数中的 PL/SQL 文件调用函数
- azure-devops - 在 Azure Devops 中使用 CMD 运行测试
- macros - 如何在 antlr4 语法中实现 typedef hack
- android-emulator - Virtual Box:运行 Android 模拟器时出现严重错误
- angular - 如何在 MatTable Angular 中进行自定义排序