-1

这是我的代码片段:

#include <json.hpp>
using json = nlohmann::json;

chat_message m; // helpter class to send the message

json j;
j["name"] = "States";
j["type "]= "Regular";
j["num"] = 4;

m.body_length( j.asString().size() ); // throws error on j.asString

我想将整个 JSON 对象更改jstd::string并将其发送到服务器。

如何将此对象转换为std::string
我尝试使用asString. 我对这个 JSON 东西很陌生。

4

2 回答 2

4

序列化 JSON 对象以获取std::stringusingjson::dump()方法。

始终首先参考文档以了解您正在使用的任何库的 API。

这是一个例子(现场):

#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;

int main()
{
    json j;
    j["name"] = "States";
    j["type"] = "Regular";
    j["num"] = 4;

    const auto s = j.dump(); // serialize to std::string
    std::cout << "JSON string: " << s << '\n';
    std::cout << "JSON size  : " << s.size() << '\n';

    return 0;
}

输出:

JSON string: {"name":"States","num":4,"type":"Regular"}
JSON size  : 42
于 2020-03-29T14:01:06.127 回答
1

将 JSON 对象转换为字符串的过程称为序列化。

根据文档,您需要调用的方法是j.dump().

这是文档中的一个示例:

// explicit conversion to string
std::string s = j.dump();    // {"happy":true,"pi":3.141}

// serialization with pretty printing
// pass in the amount of spaces to indent
std::cout << j.dump(4) << std::endl;
// {
//     "happy": true,
//     "pi": 3.141
// }
于 2020-03-29T13:51:46.073 回答