我如何使用nlohmann / json.hpp序列化2套

时间:2018-06-21 16:43:28

标签: c++ json nlohmann-json

我有两个使用Boost哈希实现的无序对(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
    }
}

1 个答案:

答案 0 :(得分:0)

您想要的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;

第二部分也是如此。

相关问题