【问题标题】:Read vector of strings value from JSON file, in C++ using Boost使用 Boost 在 C++ 中从 JSON 文件中读取字符串值的向量
【发布时间】:2019-01-15 10:58:33
【问题描述】:

我是 Boost 和 Json 的新手。 应该很简单,但是找不到答案。

如何使用 Boost 在 C++ 中读取作为字符串向量的值。

Json 文件内容举例:

{  
"keyword1": ["string1", "string2"],  
"keyword2": ["string3", "string4"] 
}

最后我想为每个关键字设置向量:

vector<string> keyword1;
vector<string> keyword2;

【问题讨论】:

  • this question 的可能重复项。简而言之,您应该先尝试,然后向社区展示您的工作以寻求帮助。

标签: c++ json boost


【解决方案1】:

在 boost 中你最好的选择是在这个问题中使用一些东西:Reading JSON with Boost property_tree

如果您需要简单一点,我强烈建议您使用https://github.com/nlohmann/jsonjson::parse API。

【讨论】:

    【解决方案2】:

    感谢您的帮助。

    这段代码对我有用:

    boost::property_tree::ptree pt;
    boost::property_tree::read_json("test.json", pt);
    BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("entry_name"))
    {
         std::cout << v.second.data() << std::endl;
    }
    

    'test.json'文件的内容:

    {
        "entry_name": ["string1", "string2", "string3"]
    }
    

    代码输出:

    string1
    string2
    string3
    

    我将补充一点,我尝试了多个字符串值的不同解析,包括:

    std::vector<std::string> vec = pt.get<std::vector<std::string>> ("entry_name");
    

    那是错误的。

    我不想添加新的类/库,例如 'rapidJson' 或 'nlohmann' ,只添加 boost 库。

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多