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

时间:2019-03-14 05:59:32

标签: c++ json jsoncpp

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


    [
      {
        "date": "Mon 24 Dec 7:47:37 2018",
        "toRecipient": "Jai",
        "subject": "Hi Jai",
        "body": "This is Tony",
        "fromRecipient": "Tony"
      },

      {
        "date": "Mon 24 Dec 7:47:38 2018",
        "toRecipient": "Jai",
        "subject": "Hi Jai 2",
        "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()中,值必须为objectValue   中止(核心已弃用)

1 个答案:

答案 0 :(得分:0)

感谢用户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
            }