C 在较旧的JSON :: NLOHMANN库中使用push_back时无匹配函数


#include "json.hpp"
#include <memory>
#include <vector>
#include <iostream>

struct json_node;
using json_node_ptr = std::shared_ptr<json_node>;
struct json_node
{
    int id;
    std::vector<json_node_ptr> children;
    json_node(int _id)
        : id{ _id }
    {
    }
};
void to_json(nlohmann::json& j, const json_node_ptr& node)
{
    j = {{"ID", node->id}};
    if (!node->children.empty()) {
        j.push_back(  nlohmann::json {"children", node->children});
        //j["children"] = node->children;
    }
}
int main()
{
}

我遇到以下错误。我该如何解决?它背后的问题是什么?

有什么容易的运动能力吗?更改客户库并不容易。

error: no matching function for call to ‘basic_json<>::push_back(<brace-enclosed initializer list>)’
             j.push_back( {"children", node->children} );

标题文件在这里:https://github.com/nlohmann/json/blob/v2.0.10/src/json.hpp

更新:此问题发生在库的较旧版本中。这是 修复了最新版本。

在这里,将结构转换为字符串的代码,然后将字符串解析为json对象

#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <string>
#include "json.hpp"
struct json_node;
using json_node_ptr = std::shared_ptr<json_node>;
struct json_node
{
    int id;
    std::vector<json_node_ptr> children;
    json_node(int _id)
        : id{ _id }
    {
    }
    std::ostringstream& print(std::ostringstream& ss) const
    {
        ss << "{"ID" :" << id ;
        if (children.size() > 0) {
            ss << ", "children" : [";
            std::string prefix = "";
            for (auto& ch : children) {
                ss << prefix;
                ch->print(ss);
                prefix = ", ";
            }
            ss << "]";
        }
        ss << "}";
        return ss;
    };
};
std::ostringstream& operator<<(std::ostringstream& ss,const json_node & node)
{
    return node.print(ss);
}
void to_json(nlohmann::json& j, const json_node_ptr& node)
{
    std::ostringstream ss;
    ss << *node;
    std::string str = ss.str();
    j = nlohmann::json::parse(str);
}
int main()
{
    json_node_ptr p = std::make_shared<json_node>(1);
    json_node_ptr child_1 = std::make_shared<json_node>(2);
    p->children.push_back(child_1);
    json_node_ptr child_2 = std::make_shared<json_node>(3);
    json_node_ptr child_3 = std::make_shared<json_node>(4);
    child_2->children.push_back(child_3);
    p->children.push_back(child_2);
    nlohmann::json j;
    to_json(j, p);
    std::cout << j << 'n';

    nlohmann::json j1 = nlohmann::json::array();
    j1.push_back(j);
    j1.push_back(p);
    std::cout << j1 << "n";
}

输出

{"ID":1,"children":[{"ID":2},{"ID":3,"children":[{"ID":4}]}]}

这是to_json的另一个速率 - 不用用于字符串序列化

void to_json(nlohmann::json& j, const json_node_ptr& node)
{
    j["ID"] = node->id;
    if (node->children.size() > 0)
    {
        j["children"] = nlohmann::json::array();
        for (auto& ch : node->children)
        {
            nlohmann::json j_child;
            to_json(j_child, ch);
            j["children"].push_back(j_child);
        }
    }
}

最新更新