如何反序列化数组?

时间:2018-10-04 12:06:31

标签: c++ json nlohmann-json

我正在使用nlohmann::json库对json中的元素进行序列化/反序列化。 这是我序列化C++双精度数组的方法:

double mLengths[gMaxNumPoints] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
...
nlohmann::json jsonEnvelope;
jsonEnvelope["lengths"] = envelope.mLengths;

哪种产品:

"lengths":[  
   1.0,
   2.0,
   3.0,
   4.0,
   5.0
]

但是现在,我如何反序列化为mLengths?尝试过:

mLengths = jsonData["envelope"]["lengths"];

但是它显示expression must be a modifiable lvalue。如何恢复阵列?

2 个答案:

答案 0 :(得分:5)

我手头没有图书馆,但应该像这样:

auto const &array = jsonData["envelope"]["lengths"];

if(!array.is_array() || array.size() != gMaxNumPoints) {
    // Handle error, bail out
}

std::copy(array.begin(), array.end(), mLengths);

std::copy舞蹈是必要的,因为顾名思义,C风格的数组是一个非常准系统的容器,其规范已从C大量复制。因此,它是不可分配的(也不能复制或移动构建。

答案 1 :(得分:5)

它与vector一起使用:

#include <iostream>
#include <nlohmann/json.hpp>                                                

int main() {
    double mLengths[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
    nlohmann::json j;
    j["lengths"] = mLengths;
    std::cout << j.dump() << "\n";

    std::vector<double> dbs = j["lengths"];
    for (const auto d: dbs)
        std::cout << d << " ";
    std::cout << "\n";

    return 0;
}

通过赋值反序列化不能用于C数组,因为您不能为它们正确定义转换运算符。

相关问题