You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++通过函数动态生成合法JSON字符串的实现问题咨询

问题诊断与修复方案

你的实现方式不正确,存在3个核心错误:

  • 拼写错误:boost::proprty_tree 应为 boost::property_tree,该错误会直接导致编译失败。
  • 序列化逻辑缺失:createJson 函数中完成 ptree 赋值后,没有调用boost::property_tree::write_json接口将树结构序列化为JSON格式写入字符串流,函数返回值永远是空字符串。
  • 拼接逻辑不符合JSON规范:直接拼接多个独立JSON对象字符串会生成{"key":"val"}{"key":"val"}的非法格式,如果需要返回多条数据,必须将其包裹为JSON数组,元素之间用英文逗号分隔。

修复后可运行示例代码

#include <iostream>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using namespace std;
namespace pt = boost::property_tree;

// 生成单个JSON对象的字符串
string createJson(const string& one, const string& two, const string& three, const string& four)
{
    pt::ptree pt;
    stringstream ss;

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

    // 新增:将ptree序列化为JSON写入流
    pt::write_json(ss, pt, false); // 第三个参数false表示不格式化输出,生成紧凑JSON适合传输
    return ss.str();
}

int main()
{
    // 这里如果要生成JSON数组,先写数组开头的[
    string jsonstr = "[";
    int m = 3; // 示例循环次数
    // 假设下方的one等变量均已初始化为任意字符串
    string one = "test1", two = "test2", three = "test3", four = "test4";
    
    for(int i = 0; i < m; i++)
    {
        string tempstr = createJson(one, two, three, four);
        if (i != 0) {
            jsonstr += ","; // 非第一个元素前加逗号分隔
        }
        jsonstr.append(tempstr);
    }
    
    // 补全数组结尾的]
    jsonstr += "]";
    cout << jsonstr << endl;
    
    return 0;
}

补充说明

如果不需要返回数组,仅需返回单个JSON对象,直接删除循环逻辑和数组包裹符号即可。另外boost.property_tree生成JSON存在一个已知限制:所有数值类型会被序列化为带引号的字符串,如果需要严格匹配数值类型,建议替换为专门的JSON库实现。

内容的提问来源于stack exchange,提问作者Dr. Essen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:15:07