【问题标题】:property_tree get array value as Stringproperty_tree 以字符串形式获取数组值
【发布时间】:2020-02-24 20:01:40
【问题描述】:

我想用 boosts property_tree 解析一个 json 文件/字符串,但我不想将子树解析成一个数组,而是希望它作为一个字符串保留在另一个仅处理 json-Strings 的现有函数中使用。

我希望下面的例子就足够了:


example.json

{
    "type": "myType",
    "colors": {
        "color0":"red",
        "color1":"green",
        "color2":"blue"
    }
}

main.cpp

std::stringstream ss("example.json");
ptree pt;
read_json(ss, pt);

std::string sType = pt.get("type", "");
std::string sColors = pt.get<std::string>("colors");

std::cout << "sType: " << sType << std::endl; // sType: myType
std::cout << "sColors: " << sColors << std::endl; // sColors: {"color0":"red", "color1":"green", "color2":"blue"}

我尝试了几个函数,例如pt.get_child("colors") 只会返回另一个 ptree,而pt.get_value&lt;std::string&gt;("colors") 会返回一个空字符串 ("")

所需的输出如下所示:

sColors: {"color0":"red", "color1":"green", "color2":"blue"}

sColors: {\"color0\":\"red\", \"color1\":\"green\", \"color2\":\"blue\"}

有没有办法为 sColors 接收所需的输出?

【问题讨论】:

    标签: c++ json c++11 boost


    【解决方案1】:

    我比预期更快地找到了一个可能的解决方案,下面的代码将提供一个令人满意的答案:

    std::stringstream os;
    write_json(os, pt.get_child("colors"), false);
    std::string sColors = os.str();
    std::cout << "sColors: " << sColors << std::endl;
    

    如果有更优雅的解决方案,请随时发布!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2016-02-20
      • 2011-10-25
      相关资源
      最近更新 更多