如何在C++中表示JSON文档的递归对象结构?

How to represent recursive Object structure of JSON Documents in C++?

本文关键字:递归 对象 结构 文档 JSON C++ 表示      更新时间:2023-10-16

我想表示一个类似 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++使用如下图所示的树结构

...JSON 结构图

我试图使用以下代码实现该表示...

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))}
}
};