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

C++使用JsonCpp生成JSON时如何保持键的插入顺序?

JsonCpp生成JSON时保留键插入顺序的解决方案

默认情况下,JsonCpp的Json::Value对象使用std::map存储键值对,序列化时会按键的字典序排序,导致输出的JSON键顺序与插入顺序不符。以下是两种可行的解决思路:

一、在JsonCpp内部实现有序键输出

JsonCpp支持通过指定对象为有序类型来保持插入顺序,具体有两种实现方式:

1. 显式创建有序Json::Value对象

在创建需要保持顺序的JSON对象时,使用带有序参数的构造函数,指定内部使用有序容器存储键值对:

// 第三个参数设为true,启用有序存储
Json::Value enreg1(Json::objectValue, Json::Value::allocator_type(), true);

修改后的完整代码:

#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>
#include <memory>

int main() {
    // 创建有序的根JSON对象
    Json::Value jsonData(Json::objectValue, Json::Value::allocator_type(), true);

    // 注册1:创建有序对象
    Json::Value enreg1(Json::objectValue, Json::Value::allocator_type(), true);
    enreg1["CAT"] = "4";
    enreg1["Long"] = "19";
    enreg1["Day"] = "0";
    enreg1["Time"] = "13:15:37:86";
    enreg1["Fspec"] = "fa12gh";

    // Item1:创建有序对象
    Json::Value Item1(Json::objectValue, Json::Value::allocator_type(), true);
    Item1["AI"] = "1a";
    Item1["CC"] = "23";
    enreg1["Item1"] = Item1;

    // 将Enreg_1添加到根对象
    jsonData["Enreg_1"] = enreg1;

    // 写入文件
    std::ofstream file("do.json");
    if (file.is_open()) {
        Json::StreamWriterBuilder builder;
        std::unique_ptr<Json::StreamWriter> jsonWriter(builder.newStreamWriter());
        jsonWriter->write(jsonData, &file);
        file.close();
        std::cout << "JSON文件生成成功。" << std::endl;
    } else {
        std::cerr << "无法打开文件进行写入。" << std::endl;
        return 1;
    }

    return 0;
}

2. 全局启用有序对象(编译时配置)

如果希望所有Json::Value对象默认保持插入顺序,可以在编译JsonCpp库时定义宏JSON_USE_ORDERED_MAP,让库默认使用有序容器替代std::map存储键值对。

二、使用替代JSON库

若觉得JsonCpp的配置过于繁琐,可选择默认支持插入顺序的轻量级JSON库:

nlohmann/json

这是一个头文件仅存的JSON库,用法简洁且默认保持键的插入顺序,示例代码如下:

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

using json = nlohmann::json;

int main() {
    json jsonData;

    json enreg1;
    enreg1["CAT"] = "4";
    enreg1["Long"] = "19";
    enreg1["Day"] = "0";
    enreg1["Time"] = "13:15:37:86";
    enreg1["Fspec"] = "fa12gh";

    json Item1;
    Item1["AI"] = "1a";
    Item1["CC"] = "23";
    enreg1["Item1"] = Item1;

    jsonData["Enreg_1"] = enreg1;

    std::ofstream file("do.json");
    if (file.is_open()) {
        file << jsonData.dump(4); // 参数4表示缩进4个空格,格式化输出
        file.close();
        std::cout << "JSON文件生成成功。" << std::endl;
    } else {
        std::cerr << "无法打开文件进行写入。" << std::endl;
        return 1;
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者Abdelaziz HAMMOUABDALLAH AZIZ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:16:27