Suppose that I'm receiving a JSON formated string from network and want to decode it in a Boost Property tree. What the best way of doing that?
Asked
Active
Viewed 531 times
1
-
Can you show some code that you have tried, and maybe someone can help you from there. – Frederik Apr 26 '16 at 17:18
-
I am surprised, as I know Spanish has article. – peterh Apr 26 '16 at 18:26
-
@peterh going for some kind of irony award, I see :) – sehe Apr 26 '16 at 21:10
1 Answers
1
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:
{ "Test": "string", "Test2": { "inner0": "string2", "inner1": "string3", "inner2": "1234" } }
string2
1234

Fernando
- 1,477
- 2
- 14
- 33