【问题标题】:Create json string dynamically using a function in C++使用 C++ 中的函数动态创建 json 字符串
【发布时间】:2021-12-11 04:32:38
【问题描述】:

我想使用 C++ 函数创建一个 json 字符串,如下面的简单示例:

string createJson(string one, string two, string three, string four)
{
    boost::proprty_tree::ptree pt;
    std::stringstream ss;

    pt.put("one", one);
    pt.put("two", two);
    pt.put("three", three);
    pt.put("four", four);

    return ss.str();
}

int main()
{
    string jsonstr, tempstr;
    //assume one below are initialised any strings
    string one, two, three, four;
    for(i = 0; i < m; i++)
    {
        tempstr = createJson(one, two, three, four);
        jsonstr.append(tempstr);
    }
    cout << jsonstr << endl;
    
    return 0;
}

输出应该是正确的 json 格式。但是当所有循环运行时,我在某个地方得到了不正确的 json 格式。 json 需要从服务器发送到客户端应用程序,并且只能使用 json 格式处理。这是正确的做法吗?

请随意假设 json 值(int、string 等)。

【问题讨论】:

  • 什么是jsonstr?那是图书馆的一部分吗?
  • boost::property_tree的目的不是json...有专门的json库...
  • 这段代码根本不输出任何东西。甚至没有数据流入ss。请发布您已验证的代码实际上会产生您所描述的现象。 proprty_tree 中甚至还有一个错字,所以你显示的代码不可能是你正在谈论的代码。
  • 这可能是个问题,但我没有看到 ss 被写入。
  • nlohmann::json 是一个出色的仅标头 C++ json 库

标签: c++ json c++11 boost


【解决方案1】:

在显示的代码中,唯一缺少的行似乎是

write_json(ss, pt);

Live On Coliru

但是

使用合适的 JSON 库!

#include <boost/json.hpp>

std::string createJson(std::string const& one, std::string const& two,
                       std::string const& three, std::string const& four)
{
    return serialize(boost::json::object{
        {"one", one},
        {"two", two},
        {"three", three},
        {"four", four},
    });
}

也可以看到Live On Coliru

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多