Po pierwsze, czy mogę zaproponować modernizacji i w ten sposób uprościć kod, unikając przy tym using
dyrektywy:
#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");
}
}
Po drugie, można wybrać nieprawidłowe poziomy-jak wskazuje inną odpowiedź.:
#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";
}
Zobaczyć to na żywo
Ale PRAWDZIWY problem polega na tym, że:
UŻYJ BIBLIOTEKI JSON
Drzewo właściwości Boost nie jest biblioteką JSON.
Boost JSON jest:
Żyć Na Колиру
#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";
}
Z nadrukami
Name: "John", Course: "C++"
bonus
Dla bardziej poważnego kodu można użyć mapowania typów:
#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";
}
Zobacz to Na Żywo Na Колиру