字符串写入到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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值