jsoncpp如何获取data内信息

{"success":true,"title":"百度热点","subtitle":"指数","update_time":"2023-02-20 08:56:02","data":[{"index":1,"title":"布林肯称中或向俄提供武器 中方驳斥","d......

我希望读取到data内index1的信息,似乎[符号阻止了我的访问。一下是jsoncpp代码,我要如何修改?


        CString str = content;
        Json::Reader reader;
        Json::Value root;
        CString temp;
        CString temp2;
        CString temp3;
        CString temp4;
        CString temp5;
        CString temp6;
        USES_CONVERSION;
        char* cJson = T2A(str.GetBuffer(0));
        str.ReleaseBuffer();
        if (reader.parse(cJson, root)) {
            temp2 = root["data"].asCString();

            MessageBox(temp2);
        }

根据提供的 JSON 数据,可以看出 "data" 对应的值是一个数组,因此需要先获取数组,然后再获取数组中的某一项数据。

可以使用 JsonCpp 库提供的 operator[] 和 get 方法来获取 JSON 数组中指定的数据项。以下是修改后的代码:

        // 解析 JSON 数据
        Json::Reader reader;
        Json::Value root;
        CString temp;
        USES_CONVERSION;
        char* cJson = T2A(content.GetBuffer(0));
        content.ReleaseBuffer();
        if (reader.parse(cJson, root)) {
            // 获取 "data" 数组
            Json::Value dataArray = root["data"];
            // 获取数组中第一项的 "index" 值
            int index = dataArray[0]["index"].asInt();
            // 获取数组中第一项的 "title" 值
            CString title = A2T(dataArray[0]["title"].asCString());
            // 显示获取到的数据
            temp.Format(_T("index: %d, title: %s"), index, title);
            MessageBox(temp);
        }


该回答引用ChatGPT

可以通过以下方式访问data内index为1的信息:

CString str = content;
Json::Reader reader;
Json::Value root;
CString temp;
CString temp2;
CString temp3;
CString temp4;
CString temp5;
CString temp6;
USES_CONVERSION;
char* cJson = T2A(str.GetBuffer(0));
str.ReleaseBuffer();
if (reader.parse(cJson, root)) {
    Json::Value data = root["data"];
    if (data.isArray() && data.size() > 0) {
        Json::Value item = data[0];
        int index = item["index"].asInt();
        if (index == 1) {
            temp2 = item["title"].asCString();
            // 其他字段的获取
        }
    }
}
MessageBox(temp2);


这样可以访问到data内的第一个元素,然后判断其index是否为1,如果是,则可以获取该元素内的其他信息。注意,在上述代码中,假设data是一个数组,因此可以使用data.isArray()判断是否为数组,同时通过data.size()获取元素数量。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^