如何使用 nlohmann::json 将 json 对象转换为地图?

新手上路,请多包涵

例如,使用 nlohmann::json,我可以做到

map<string, vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;

但我做不到

m = j;

有什么方法可以使用 nlohmann::json 将 json 对象转换为地图?

原文由 user1899020 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 853
1 个回答

nlomann::json 可以使用 get<typename BasicJsonType>() const 将 Json 对象转换为大多数标准 STL 容器

例子:

 // Raw string to json type
auto j = R"(
{
  "foo" :
  {
    "bar" : 1,
    "baz" : 2
  }
}
)"_json;

// find object and convert to map
std::map<std::string, int> m = j.at("foo").get<std::map<std::string, int>>();
std::cout << m.at("baz") << "\n";
// 2

原文由 Fred 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题