首页 > 解决方案 > 如何在 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++ 中使用树结构,如下图所示...

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

标签: c++jsonrecursion

解决方案


JSONObject o
    {
        {"string", std::variant<JSONType, JSONObject>(JSONType(true))}
    };

缺少一组大括号。您需要一组用于JSONObject,一组用于attributes成员,最后一组用于映射条目:

JSONObject o
    {
      {
        {"string", std::variant<JSONType, JSONObject>(JSONType(true))}
      }
    };

推荐阅读