首页 > 解决方案 > 如何将结构向量写入 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"
}

我在这里想念什么?

标签: c++jsonnlohmann-json

解决方案


感谢 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"
  }
]

推荐阅读