【问题标题】:nlohmann's json library convert an array to a vector of structsnlohmann json 库将数组转换为结构向量
【发布时间】:2020-02-20 17:53:03
【问题描述】:

假设我有一个如下所示的 json 数组:

[
  {
    "Name": "test",
    "Val": "test_val"
  },
  {
    "Name": "test2",
    "Val": "test_val2"
  }
]

我想将其转换为结构向量:

struct Test {
  string Name;
  string Val;
};

我知道json.get<>() 方法,但不知道如何将其应用于此。

【问题讨论】:

    标签: c++ json nlohmann-json


    【解决方案1】:

    为了使自动 get<> 工作,您需要提供 JSON 和您的结构之间的映射:

    void from_json(const nlohmann::json& j, Test& p) {
        j.at("Name").get_to(p.Name);
        j.at("Val").get_to(p.Val);
    }
    

    然后它将按预期工作。

    auto parsed = json.get<std::vector<Test>>();
    

    演示:https://godbolt.org/z/9P1mjO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2013-05-15
      • 2021-08-02
      相关资源
      最近更新 更多