c++ - 我如何决定 Boost Property Tree 使用的数据类型?

标签 c++ json boost boost-propertytree

我正在为项目使用 Boost 属性树,但遇到了问题。我这样使用它:

using Namespace boost::property_tree;
ptree proot;

int myInt = 5;

proot.put("Number", myInt);

write_json("myjson.json", proot);

如果我像这样使用它,则安全的数据类型是字符串,而不是 int。我的意思的一个例子:

{ "Number": "5" } //what i get
{ "Number": 5 } //what i want

有办法改变吗?

最佳答案

不,您无法更改此行为,因为字符串值类型几乎已融入到 boost::property_tree 中。虽然从技术上讲您可以使用与默认参数不同的模板类型参数,但您会丢失该库中的大部分转换逻辑。

作为一个有点古怪的替代方案,请考虑以下内容。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using namespace boost::property_tree;
using boost::property_tree::json_parser::create_escapes;

void writeJsonValue(std::ostream& stream, const ptree& pt)
{
    const auto raw = pt.get_value<std::string>();

    if (raw == "true" || raw == "false") {
        stream << raw;
        return;
    }

    if (const auto integral = pt.get_value_optional<int>())
        stream << *integral;
    else
        stream << '"' << create_escapes(raw) << '"';
}

这本质上恢复了一些预定义的类型信息丢失。您可以在 Boost json 输出函数的修改版本中使用它:

void writeJson(std::ostream& stream, const ptree& pt, int indent = 0)
{
    static const auto indentStr = [](int level) { return std::string(4 * level, ' '); };

    if (indent > 0 && pt.empty())
        writeJsonValue(stream, pt);
    else if (indent > 0 && pt.count(std::string()) == pt.size()) {
        stream << "[\n";

        for (auto it = pt.begin(); it != pt.end(); ++it) {
            stream << indentStr(indent + 1);
            writeJson(stream, it->second, indent + 1);
            if (boost::next(it) != pt.end())
                stream << ',';
            stream << '\n';
        }

        stream << indentStr(indent) << ']';
    } else {
        stream << "{\n";

        for (auto it = pt.begin(); it != pt.end(); ++it) {
            stream << indentStr(indent + 1);
            stream << '"' << create_escapes(it->first) << "\": ";
            writeJson(stream, it->second, indent + 1);
            if (boost::next(it) != pt.end())
                stream << ',';
            stream << '\n';
        }

        stream << indentStr(indent) << '}';
    }
}

调用它来获取您的数据,例如作为

 writeJson(std::cout, proot);

输出应该是

{
    "Number": 5
}

关于c++ - 我如何决定 Boost Property Tree 使用的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64044195/

相关文章:

c++ - Visual C++ 6初学者教程

c++ - 如何使用 lambda 函数打印一对<>?

javascript - 莫名其妙地无法在 d3.js map : out of scope NAME? 上呈现城市名称标签

c++ - Armadillo 与 Boost Odeint : Odeint resizes the state vector to zero during integration 冲突

c++ - 使用 Boost::spirit 编写的解析器的性能问题

c++ - 对 fstream 和指针感到困惑

c++ - std::auto_ptr 错误

java - 使用 Gson 将 json 字段反序列化为不同的 Java 对象

c# - 将日期时间转换为 JSON 数据有困难

c++ - 定义可变大小的元组