mar*_*zzz 0 c++ json nlohmann-json
我正在使用nlohmann :: json库来序列化/反序列化元素json.这是我如何序列化C++double数组:
double mLengths[gMaxNumPoints] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
...
nlohmann::json jsonEnvelope;
jsonEnvelope["lengths"] = envelope.mLengths;
Run Code Online (Sandbox Code Playgroud)
哪个产品:
"lengths":[
1.0,
2.0,
3.0,
4.0,
5.0
]
Run Code Online (Sandbox Code Playgroud)
但现在,我怎样才能反序列化mLengths?试过:
mLengths = jsonData["envelope"]["lengths"];
Run Code Online (Sandbox Code Playgroud)
但它说expression must be a modifiable lvalue.如何恢复阵列?
我手边没有库,但应该是这样的:
auto const &array = jsonData["envelope"]["lengths"];
if(!array.is_array() || array.size() != gMaxNumPoints) {
// Handle error, bail out
}
std::copy(array.begin(), array.end(), mLengths);
Run Code Online (Sandbox Code Playgroud)
该std::copy舞蹈是必要的,因为C风格的数组,正如它的名字所暗示的,一个非常裸机容器,其规格已经几乎从C复制因此,它是不能转让(也不禁止复制或移动,constructible要么).
它适用于矢量:
#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;
}
Run Code Online (Sandbox Code Playgroud)
通过赋值进行反序列化不适用于C数组,因为您无法为它们正确定义转换运算符.
| 归档时间: |
|
| 查看次数: |
251 次 |
| 最近记录: |