C++ JSON解析错误...在Json::Value::getMemberNames()中,值必须为对象值错误

kr98yfug  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(366)

我正在尝试解析下面的json文件:

[
      {
        "date": "Mon 24 Dec 7:47:37 2018",
        "toRecipient": "Vinny",
        "subject": "Hi Vinny",
        "body": "This is Tony",
        "fromRecipient": "Tony"
      },
      
      {
        "date": "Mon 24 Dec 7:47:38 2018",
        "toRecipient": "Vinny",
        "subject": "Hi Vinny2",
        "body": "This is Tony 2",
        "fromRecipient": "Tony"
      },
    etc...

这是我的解析函数

MessageLibrary::MessageLibrary(string jsonFileName) {
            Json::Reader reader;
            Json::Value root;
            std::ifstream json(jsonFileName.c_str(), std::ifstream::binary);
            bool parseSuccess = reader.parse(json, root, false);
        
            if (parseSuccess) {
                Json::Value::Members mbr = root.getMemberNames();
                for(vector<string>::const_iterator i = mbr.begin(); i!= mbr.end(); i++) {
                    Json::Value jsonMessage = root[*i];
        
                    string date = jsonMessage["date"].asString();
                    string toRecipient = jsonMessage["toRecipient"].asString();
                    string subject = jsonMessage["subject"].asString();
                    string body = jsonMessage["body"].asString();
                    string fromRecipient = jsonMessage["fromRecipient"].asString();
        
                    // create Message objects from parse
                    Message *message = new Message(toRecipient, fromRecipient, subject, body, date);
                    messages[*i] = *message;
}

当我调用Json::Value::Members mbr = root.getMemberNames();时,错误似乎出现了,我不知道如何解决这个问题。
在引发“Json::LogicError”的示例后调用了terminate
what():在Json::Value::getMemberNames()中,值必须是对象值已中止(核心转储)

qyzbxkaa

qyzbxkaa1#

多亏了用户xyz347,我才意识到我的整个JSON是一个数组,需要以不同的方式循环,如下所示:

if (parseSuccess) {
            for(Json::Value::ArrayIndex i = 0; i != root.size(); i++) {

                string date = root[i]["date"].asString();
                string toRecipient = root[i]["toRecipient"].asString();
                string subject = root[i]["subject"].asString();
                string body = root[i]["body"].asString();
                string fromRecipient = root[i]["fromRecipient"].asString();

                // create Message objects from parse
                Message *message = new Message(toRecipient, fromRecipient, subject, body, date);
                // messages[*i] = *message;    // this doesn't work though
            }

相关问题