【问题标题】:how can I serialize 2 sets using nlohmann/json.hpp如何使用 nlohmann/json.hpp 序列化 2 个集合
【发布时间】:2018-06-21 16:43:28
【问题描述】:

我有两组使用 boost hash 实现的无序对 (X,Y),我想将它们转换为具有特殊格式的 Json 文件。

unordered_set<pair<int,int>> visited, cleaned

。我希望使用 nlohmann/json.hpp C++ 以 Json 格式表示它们:

{
  "visited": [
    {
      "X": 2,
      "Y": 2
    },
    {
      "X": 3,
      "Y": 0
    },
    {
      "X": 3,
      "Y": 1
    },
    {
      "X": 3,
      "Y": 2
    }
  ],
  "cleaned": [
    {
      "X": 2,
      "Y": 2
    },
    {
      "X": 3,
      "Y": 0
    },
    {
      "X": 3,
      "Y": 2
    }
  ],
}

谁能帮我编写这部分的 c++ 代码? 我的代码是

for (auto it = visited.begin(); it != visited.end(); ++it)
    {
        j2["visited"]["X"]=it->second;
        j2["visited"]["Y"] = it->first;
    }   
    for (auto it = cleaned.begin(); it != cleaned.end(); ++it)
    {
        j2["cleaned"]["X"] = it->second;
        j2["cleaned"]["Y"] = it->first;
    }

它产生:

{
    "cleaned": {
        "X": 3,
        "Y": 2
    },
    "visited": {
        "X": 3,
        "Y": 2
    }
}

【问题讨论】:

    标签: c++ json nlohmann-json


    【解决方案1】:

    您想要的 JSON 格式包含数组。使用类似这样的东西来显式创建 他们:

    nlohmann::json arr;
    for (auto it = visited.begin(); it != visited.end(); ++it) {
        nlohmann::json o;
        o["X"] = it->second;
        o["Y"] = it->first;
        arr.push_back(o);
    }
    
    j2["visited"] = arr;
    

    第二部分也是如此。

    【讨论】:

    • 我已经这样做了:my_json j2; j2["visited"] = {}; for (auto it = visited.begin(); it != visited.end(); ++it) { j2["visited"] += { {"X", it-&gt;second}, { "Y",it-&gt;first } }; } 并且效果很好。非常感谢
    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2016-01-26
    • 2015-08-31
    • 2021-03-25
    相关资源
    最近更新 更多