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

如何使用jsoncpp创建指定格式JSON数组并整合到已有对象中?

解决JsonCpp创建坐标数组并整合到现有JSON对象的问题

别担心,这个问题其实很容易搞定!既然你已经能熟练操作JsonCpp的基础语法,那创建目标格式的Cords数组并整合到event里只需要几个简单步骤:

完整示例代码

#include <json/json.h>
#include <iostream>

int main() {
    // 你已有的基础操作
    Json::Value event;
    event["name"] = "Joe";
    event["Direction"]["left"]["x"] = "1338";
    event["Direction"]["right"]["x"] = "1337";

    // 开始创建Cords数组
    Json::Value cordsArray(Json::arrayValue); // 初始化一个空数组

    // 创建第一个坐标对象并添加到数组
    Json::Value cord1;
    cord1["x"] = 10;
    cord1["y"] = 20;
    cordsArray.append(cord1);

    // 创建第二个坐标对象并添加到数组
    Json::Value cord2;
    cord2["x"] = 70;
    cord2["y"] = 40;
    cordsArray.append(cord2);

    // 创建第三个坐标对象并添加到数组
    Json::Value cord3;
    cord3["x"] = 15;
    cord3["y"] = 65;
    cordsArray.append(cord3);

    // 将数组整合到event对象中
    event["Cords"] = cordsArray;

    // 输出完整的JSON(用StyledWriter格式化输出,方便阅读)
    Json::StyledWriter styledWriter;
    std::cout << styledWriter.write(event) << std::endl;

    return 0;
}

关键说明

  • 首先用Json::Value cordsArray(Json::arrayValue);初始化一个数组类型的Json::Value对象,这是创建JSON数组的核心步骤
  • 每个坐标都是独立的Json::Value对象,设置好x和y值后,用append()方法添加到数组里
  • 最后直接把数组赋值给event["Cords"],就完成了整合
  • 如果需要紧凑的输出格式,可以换成Json::FastWriter代替StyledWriter

运行这段代码后,你会得到包含目标Cords数组的完整JSON输出,完全符合你的需求~

内容的提问来源于stack exchange,提问作者JJ Jones

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:57:41