简体   繁体   English

如何将 std::string 格式的 JSON 解码为 Boost 属性树?

[英]How to decode an std::string formated JSON into a Boost Property tree?

Suppose that I'm receiving a JSON formated string from network and want to decode it in a Boost Property tree.假设我从网络接收到一个 JSON 格式的字符串,并想在 Boost 属性树中对其进行解码。 What the best way of doing that?这样做的最佳方法是什么?

For creating a easy example, lets assume we have a string in the code to represent the string that you are going to receive from the network with the following content:为了创建一个简单的示例,假设我们在代码中有一个字符串来表示您将从网络接收的字符串,内容如下:

{
    "Test": "string",
    "Test2":
    {
        "inner0": "string2",
        "inner1": "string3",
        "inner2": "1234"
    }
}

So the code for interpreting that as a string is the following:因此,将其解释为字符串的代码如下:

#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <sstream>

int main()
{
    std::stringstream buffer("{ \"Test\": \"string\", \"Test2\": { \"inner0\": \"string2\", \"inner1\": \"string3\", \"inner2\": \"1234\" } }");
    std::cout << buffer.str() << std::endl;

    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json(buffer, pt);

    std::string test2_inner0_str = pt.get<std::string>("Test2.inner0");
    int test2_inner2_value = pt.get<int>("Test2.inner2");

    std::cout << test2_inner0_str << std::endl;
    std::cout << test2_inner2_value << std::endl;
}

Prints:印刷:

Live On Coliru 住在 Coliru

{ "Test": "string", "Test2": { "inner0": "string2", "inner1": "string3", "inner2": "1234" } }
string2
1234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM