Reputation: 47945
I'm using the nlohmann::json library to serialize/deserialize elements in json
.
Here's how I serialize a C++
array of double:
double mLengths[gMaxNumPoints] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
...
nlohmann::json jsonEnvelope;
jsonEnvelope["lengths"] = envelope.mLengths;
Which produce:
"lengths":[
1.0,
2.0,
3.0,
4.0,
5.0
]
But now, how can I deserialize back to mLengths
? Tried with:
mLengths = jsonData["envelope"]["lengths"];
But it says expression must be a modifiable lvalue
. How can I restore back the array?
Upvotes: 0
Views: 1771
Reputation: 63124
I don't have the library at hand, but it should be something like:
auto const &array = jsonData["envelope"]["lengths"];
if(!array.is_array() || array.size() != gMaxNumPoints) {
// Handle error, bail out
}
std::copy(array.begin(), array.end(), mLengths);
The std::copy
dance is necessary because a C-style array is, as its name implies, a very bare-bones container whose specifications has been pretty much copied over from C. As such, it is not assignable (nor copy- or move-constructible either).
Upvotes: 5
Reputation: 891
It works with 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;
}
Deserialization via assignment is not gonna work with C arrays, because you can't properly define a conversion operator for them.
Upvotes: 6