【问题标题】:Read from json file value in a vector从向量中的 json 文件值读取
【发布时间】:2021-08-18 17:29:14
【问题描述】:

想要从 json 中读取结构元素的向量。 JSON:

答:[ { “列表” :[ “a2, “b”:4, “c”:9 ] }

我的向量是:std::vector vec;

structE{ "a", "b", "c" }

              if (A[i].isMember("list")) // && 
                  {
                      auto const list= A[i]["list"];
                      for (auto i2 = 0u; i2 < list.size(); i2++)
                      {
                          vec.push_back(list[i2]["list"]);
                      }
                  }

我有这个错误:调用'std::vector ::push_back(const Json::Value&)'的匹配函数

【问题讨论】:

  • 您期望A[i]["list"] 是什么?第二个[] 中的表达式计算为指向const char 的指针。

标签: c++ json


【解决方案1】:

我有这个错误:调用'std::vector ::push_back(const Json::Value&)'的匹配函数

从您的源代码中,看来您可能正在使用 JsonCpp 在 C++ 代码中处理 Json,在处理 Json::Value 对象时,对于基本类型,例如 intstd::string,您可以分别使用Json::Value::asInt()Json::Value::asString(),但是,对于结构,您需要手动提取值并使用这些值构造结构的对象:

struct E {
    int a, b, c;
};

// ...

E createEFromJsonValue(Json::Value const& obj) {
    // Create an object of struct E with values taken from the JSON object
    return {
               obj.get("a", Json::nullValue).asInt(),
               obj.get("b", Json::nullValue).asInt(),
               obj.get("c", Json::nullValue).asInt(),
           };
}

那么你可以这样做:

// ...
vec.push_back(createEFromJsonValue(list[i2]["list"]));
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2012-10-25
    • 2013-12-10
    相关资源
    最近更新 更多