簡體   English   中英

從向量中讀取 json 文件值

[英]Read from json file value in a vector

想從 json 中讀取結構元素的向量。JSON:

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

我的向量是:std::vector<structE>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"]); } }

我有這個錯誤:匹配 function 以調用 'std::vector::push_back(const Json::Value&)'

我有這個錯誤:匹配 function 以調用 'std::vector::push_back(const Json::Value&)'

從您的源代碼來看,您可能正在使用JsonCpp來處理 Json 代碼中的 C++,在處理Json::Value對象時,對於intstd::string等基本類型,您可以使用Json::Value::asInt()Json::Value::asString()分別,但是,對於結構,您需要手動提取值並使用這些值構造結構的 object:

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"]));
// ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM