将json对象转换为字符串boost

时间:2017-01-14 16:55:42

标签: c++ json boost

我是stackoverflow的新手抱歉,如果我有任何错误,请纠正我,如果我错了。我在boost中做了很多关于json解析器和xml解析器的研究。我想做的事情是,假设我有一个json,如下所示

      {
           "topology_1":{
           "clnt_id":"aldgdsgsd",
           "sensors":{
                       "num_sensors":"6",
                        "sensor_1":{
                                     "time_interval":"5#15",
                                     "min_bound":"",
                                     "max_bound":"54",
                                     "anomaly":"2%",
                                     "anomaly_window":"70",
                                     "jump":"10",
                                     "topic":"sense/thubrahali/temp",
                                      "qos":"1"
                                   }
                     }
         }
     }

我想将从boost jsonparser获取的'topology'的值转换为字符串,以便将它存储在容器中的某个位置以供以后使用。现在我无法直接通过theboost库获取值,因为它将其视为一个json对象。我该如何将这个值转换为字符串。

1 个答案:

答案 0 :(得分:3)

通常的警告适用,boost没有JSON库。如果你留在Boost Property Tree提供的子集中,你可以:

std::string as_json_string(ptree const& pt) {
    std::ostringstream oss;
    write_json(oss, pt);
    return oss.str();
}

演示

<强> Live On Coliru

#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using boost::property_tree::ptree;

std::string as_json_string(ptree const& pt) {
    std::ostringstream oss;
    write_json(oss, pt);
    return oss.str();
}

int main() {
    std::istringstream iss(R"({
        "topology_1": {
            "clnt_id": "aldgdsgsd",
            "sensors": {
                "num_sensors": "6",
                "sensor_1": {
                    "time_interval": "5#15",
                    "min_bound": "",
                    "max_bound": "54",
                    "anomaly": "2%",
                    "anomaly_window": "70",
                    "jump": "10",
                    "topic": "sense/thubrahali/temp",
                    "qos": "1"
                }
            }
        }
    })");

    ptree document;
    read_json(iss, document);

    // and back to string
    std::string topology_1 = as_json_string(document.get_child("topology_1"));

    std::cout << topology_1;
}

打印

{
    "clnt_id": "aldgdsgsd",
    "sensors": {
        "num_sensors": "6",
        "sensor_1": {
            "time_interval": "5#15",
            "min_bound": "",
            "max_bound": "54",
            "anomaly": "2%",
            "anomaly_window": "70",
            "jump": "10",
            "topic": "sense\/thubrahali\/temp",
            "qos": "1"
        }
    }
}