JSONCPP附加文件

JSONCPP append to file

本文关键字:文件 JSONCPP      更新时间:2023-10-16

我正在使用JSONCPP来记录我在服务器上收到的消息,但是它没有附加消息,而是替换了最后一条消息。这是我拥有的代码:Ofstream和事件是私人成员。

  //std::ofstream myfile;
  m_file.open ("messageLogs.json");
  //Json::Value event;
  Json::Value array(Json::arrayValue);
  array.append(Json::Value(1));
  array.append(Json::Value(1));
  m_event["messages"]["time"] = "19:22";
  m_event["messages"]["message"] = msg;
  //populate object with objects
  Json::StyledWriter writer;
  m_file << writer.write(m_event) << std::endl;
  m_file.close();

您可以将文件加载为Json::Value对象,然后在此附加。请注意,此代码段要求JSON具有数组作为文件中的顶级项目,例如:

Messagelogs.json

[]

main.cpp

#include <iostream>
#include <fstream>
#include <json/json.h>
int main(int argc, char* argv[])
{   
    std::fstream m_file;
    m_file.open ("messageLogs.json", std::ios::in);
    Json::Reader reader;
    Json::Value json_obj;
    if(!reader.parse(m_file, json_obj, true))
    {
        // json file must contain an array
        std::cerr << "could not parse the json file" << std::endl;
        return -1;
    }
    m_file.close();
    Json::Value m_event;
    m_event["messages"]["time"] = "19:22";
    m_event["messages"]["message"] = "Some message";//msg;
    // append to json object
    json_obj.append(m_event);
    std::cout << json_obj.toStyledString() << std::endl;
    // write updated json object to file
    m_file.open("messageLogs.json", std::ios::out);
    m_file << json_obj.toStyledString() << std::endl;
    m_file.close();
    return 0;
}