【问题标题】:nlohmann : Write json to a TCP socket (and also receive) [duplicate]nlohmann:将 json 写入 TCP 套接字(并接收)[重复]
【发布时间】:2022-11-18 02:21:16
【问题描述】:

我必须将 JSON 转换为原始数据,然后将其写入文件。我找到了以下示例:

#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{

    json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;

    std::cout << j.dump() << std::endl;

    //convert json to string 
    std::string s = j.dump ();  
    //convert from string to stream 
    const char *pData = s.c_str();  

    //convert from stream to string
    std::string out(pData );
}

还是不知道反方向怎么做。

【问题讨论】:

  • 当问题是关于编译器错误时,您应该在问题中包括编译器错误。如果您发布其他人编写的代码,您应该提供对源代码的引用
  • 你是什​​么意思原始数据j.dump() 返回一个字符串。那是您想保存到文件中的内容吗?就我个人而言,我不会将字符串称为原始数据,但也许您的想法不同。
  • @k314159 缺少括号似乎是编译错误的原因
  • 你读过documentation了吗?
  • 为什么是fopenstd::ofstream 出了什么问题

标签: c++ json


【解决方案1】:

为什么不直接使用 fstream 呢?然后它just works

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    auto file = std::ofstream{"dump.bin"};
    auto j = "{ "happy": true, "pi": 3.141 }"_json;
    file << j;
    // File closes automatically at end of scope
}

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 2020-01-12
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2013-03-13
    • 2015-08-04
    相关资源
    最近更新 更多