首页 > 解决方案 > 如何从json文件读取值数组到c++数组

问题描述

我有一个带有值和一组值的 sample.json。我目前正在使用 Json 库来解析 json 文件并将内容读入 C++ 代码。我知道如何读取值但不确定读取数组

下面是 sample.json 文件的内容。

"steering_facts" :
{
    "SteerPolynomial": [0.0, 0.0, -0.0006148, 0.025, 16.24, -0.3823],
    "SteerRatio"     : 0.0
}

在这里,我可以借助以下代码阅读“SteerRatio”。

static Json::Value  jsonValues;
if (jsonValues.isMember("steering_facts")){
    float steerRatio = jsonValues["steering_facts"]["SteerRatio"].asFloat();
}

但不确定如何读取 SteerPolynomial 数组。

标签: c++json

解决方案


您可以通过以下方式编写。

static Json::Value  jsonValues;
if (jsonValues.isMember("steering_facts")){
    float steerRatio = jsonValues["steering_facts"]["SteerRatio"].asFloat();
    const Json::Value mynames = jsonValues["steering_facts"]["SteerPolynomial"];
    for ( int index = 0; index < mynames.size(); ++index )
    {
        float poli = mynames[index].asFloat();
    }
}

推荐阅读