c++ - 如何将结构向量写入 json 文件?
问题描述
基本上,这个问题与这个问题相反。
我想写一个结构向量
struct Test {
std::string Name;
std::string Val;
};
到一个文件中:
[
{
"Name": "test",
"Val": "test_val"
},
{
"Name": "test2",
"Val": "test_val2"
}
]
到目前为止我所拥有的:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <nlohmann/json.hpp>
using nlohmann::json;
struct Test {
std::string Name;
std::string Val;
};
void to_json(json& j, const Test& t)
{
j = json{ {"Name", t.Name}, {"Val", t.Val} };
}
int main(){
Test t1{"Max", "value1"};
Test t2{"Kai", "value2"};
json j1 = t1;
json j2 = t2;
std::ofstream o("test_out.json");
o << std::setw(4) << j1 << std::endl;
o << std::setw(4) << j2 << std::endl;
return 0;
}
这给了我:
{
"Name": "Max",
"Val": "value1"
}
{
"Name": "Kai",
"Val": "value2"
}
我在这里想念什么?
解决方案
感谢 Thomas 在评论中的提示,我得到了它的工作:
int main(){
Test t1{"Max", "value1"};
Test t2{"Kai", "value2"};
json j;
j.push_back(t1);
j.push_back(t2);
std::ofstream o("test_out.json");
o << std::setw(4) << j << std::endl;
return 0;
}
给
[
{
"Name": "test",
"Val": "test_val"
},
{
"Name": "test2",
"Val": "test_val2"
}
]
推荐阅读
- c# - 如何将一个 web api 控制器方法调用到另一个 web api 项目中?
- java - 在 unix 中运行 spring 批处理作业
- assembly - 各汇编指令指令长度表
- apache-spark - pyspark 相当于将常量数组作为列添加到数据帧
- autoit - 有没有办法在 BrowserStack 上运行 AutoIT 脚本?
- javascript - 使用标志变量显示/隐藏 ASP.NET MVC 中的元素
- python - 从字典列表中查找值
- r - 如何在 R 中的线图中进行中断或空白
- intellij-idea - intelliJ 中 POM.xml 中的这个 O 符号是什么
- python - 如何使用在另一个类中定义的实例