在 C++ 中使用 BOOST_FOREACH 从 JSON 数组读取值时出现异常

Getting an exception when reading values using BOOST_FOREACH from the JSON array in C++

使用 BOOST_FOREACH:

读取值时出现以下错误
Unhandled exception at 0x76FCB502 in JSONSampleApp.exe: Microsoft C++ exception: boost::wrapexcept<boost::property_tree::ptree_bad_path> at memory location 0x00CFEB18.

有人可以帮助我如何从具有以下 JSON 格式的数组中读取值吗?

#include <string>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>

using namespace std;

using boost::property_tree::ptree;

int main()
{
const char* f_strSetting = R"({"Class": [{"Student": {"Name":"John","Course":"C++"}}]})";

    boost::property_tree::ptree pt1;
    std::istringstream l_issJson(f_strSetting);
    boost::property_tree::read_json(l_issJson, pt1);

    BOOST_FOREACH(boost::property_tree::ptree::value_type & v, pt1.get_child("Class.Student"))
    {
        std::string l_strName;
        std::string l_strCourse;
        l_strName = v.second.get <std::string>("Name");
        l_strCourse = v.second.get <std::string>("Course");

        cout << l_strName << "\n";
        cout << l_strCourse << "\n";
    }

    return 0;
}

你昨天问了一个非常相似的问题。我们告诉过您不要滥用 属性 树库来解析 JSON。我什至预料到:

以下是您如何从该答案展开以立即将整个数组解析为一个向量:

Live On Coliru

#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) {
        std::cerr << "DEBUG: " << v << "\n";
        auto const& s = v.at("Student");
        return {
            value_to<std::string>(s.at("Name")),
            value_to<std::string>(s.at("Course")),
        };
    }
};

using Class = std::vector<Student>;

int main()
{
    auto doc = json::parse(R"({ "Class": [
            { "Student": { "Name": "John", "Course": "C++" } },
            { "Student": { "Name": "Carla", "Course": "Cobol" } }
        ]
    })");
    auto c = value_to<Class>(doc.at("Class"));

    for (Student const& s : c)
        std::cout << "Name: " << s.name << ", Course: " << s.course << "\n";
}

打印

Name: John, Course: C++
Name: Carla, Course: Cobol

我什至加入了一个方便的调试行,以防你需要帮助弄清楚你在某个时候得到了什么:

DEBUG: {"Student":{"Name":"John","Course":"C++"}}
DEBUG: {"Student":{"Name":"Carla","Course":"Cobol"}}