gpt4 book ai didi

c++ - 如何将结构 vector 写入 json 文件?

转载 作者:行者123 更新时间:2023-12-04 07:53:16 41 4
gpt4 key购买 nike

基本上,这个问题与this one相反.

我想写一个结构 vector

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++ - 如何将结构 vector 写入 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66836172/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com