Za prvé, navrhuji modernizaci a tak zjednodušit kód, přičemž se zabrání using
směrnice:
#include <boost/property_tree/json_parser.hpp>
#include <string>
using boost::property_tree::ptree;
int main() {
ptree pt;
{
std::istringstream l_issJson( R"({"Student": {"Name":"John","Course":"C++"}})");
read_json(l_issJson, pt);
}
for(auto& [k,v] : pt.get_child("Student")) {
auto name = v.get<std::string>("Name");
auto course = v.get<std::string>("Course");
}
}
Za druhé, vyberete špatnou úrovní - jako druhá odpověď poukazuje.:
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <string>
using boost::property_tree::ptree;
int main() {
ptree pt;
{
std::istringstream l_issJson( R"({"Student": {"Name":"John","Course":"C++"}})");
read_json(l_issJson, pt);
}
auto name = pt.get<std::string>("Student.Name");
auto course = pt.get<std::string>("Student.Course");
std::cout << "Name: '" << name << "', Course: '" << course << "'\n";
}
Vidět to Live
Ale SKUTEČNÝ problém je:
POUŽÍVAT JSON KNIHOVNA
Zvýšení Majetku Strom je ne JSON knihovna.
Podporu JSON existuje:
Žít Na Coliru
#include <boost/json.hpp>
#include <boost/json/src.hpp> // for header-only
#include <iostream>
#include <string>
namespace json = boost::json;
int main() {
auto pt = json::parse(R"({"Student": {"Name":"John","Course":"C++"}})");
auto& student = pt.at("Student");
auto name = student.at("Name").as_string();
auto course = student.at("Course").as_string();
std::cout << "Name: " << name << ", Course: " << course << "\n";
}
Otisky
Name: "John", Course: "C++"
BONUS
Pro vážnější kód, možná budete chtít použít typ-mapování:
#include <boost/json.hpp>
#include <boost/json/src.hpp> // for header-only
#include <iostream>
#include <string>
namespace json = boost::json;
struct Student {
std::string name, course;
friend Student tag_invoke(json::value_to_tag<Student>, json::value const& v) {
return {
json::value_to<std::string>(v.at("Name")),
json::value_to<std::string>(v.at("Course")),
};
}
};
int main()
{
auto doc = json::parse(R"({"Student": {"Name":"John","Course":"C++"}})");
auto s = value_to<Student>(doc.at("Student"));
std::cout << "Name: " << s.name << ", Course: " << s.course << "\n";
}
Vidět to Live Na Coliru