첫째,내가 제안을 현대화하고 따라서 단순화 코드,피하는 동안 using
지침:
#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");
}
}
둘째,당신은 선택을 잘못 수준-다른 대답습니다.:
#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";
}
보 Live
하지만 진짜 문제는:
사용 JSON 라이브러리
부산 트리 지 JSON 라이브러리입니다.
부 JSON 있:
라이브에 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";
}
인쇄
Name: "John", Course: "C++"
보너스
더 많은 심각한 코드를 사용할 수 있습 유형 매핑:
#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";
}
그것을 참조 라이브에 Coliru