首页 > 解决方案 > 如何反序列化一个数组?

问题描述

我正在使用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。如何恢复阵列?

标签: c++jsonnlohmann-json

解决方案


它适用于矢量:

#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 数组,因为您无法为它们正确定义转换运算符。


推荐阅读