字符串写入到json文件

背景: PHP产生公告 ,发送到CGI ,在CGI把该公告的json 字符串写入到文件内(转义后的字符串)

通过 jsoncpp 操作

    int write_notice_to_json(string str_path, const string& str_content)
    {  
        Json::Reader reader;
        Json::FastWriter writer;
        Json::Value root;
        if (false == reader.parse(str_content, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素
        {
            return  RESULT_ERROR; 
        } 

        std::string json_file = writer.write(root);
        ofstream ofs;
        ofs.open(str_path.c_str(), ofstream::out);
        if (ofs.is_open())
        {
            ofs << json_file;
            ofs.close(); 
            return  RESULT_OK;
        } 
        return  RESULT_ERROR;
    }  

今天来到公司终于搞定了  mark一下

收到的字符串内容:

{"Notice":{"NoticeVersion":"1414","noticeContent":[{"Image":"notice\/notice01","ImageWidth":"350","ImageHeight":"5"},{"Image":"notice\/notice02","ImageWidth":"350","ImageHeight":"5"},"jghjfghjfghj"]}}

存到文件后

踩的坑:一开始想通过C++ 替换掉转义字符串 但是不起作用

 CStringUtils::Replace(m_str_content, "\"", """);

 //====================================================================================

补充:

之后调整发现,上面的全是费工夫,直接写入到文件就行了,写入文件之后,如果字符串内容是json,那就可以直接解释成json了

 1     int write_notice_to_txt(string str_path, const string& str_content)
 2     {
 3         ofstream ofs;
 4         ofs.open(str_path.c_str(), ofstream::out);
 5         if (ofs.is_open())
 6         {
 7             ofs << str_content;
 8             ofs.close();
 9             return  RESULT_OK;
10         }
11         return  RESULT_ERROR;
12     }
原文地址:https://www.cnblogs.com/Jimmy104/p/8279695.html