0

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?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
markzzz
  • 47,390
  • 120
  • 299
  • 507
  • I don't know the library you are using (although I am now looking at it) but the variable you are assigning to is a fixed array. You might want to use a vector which from a cursory look at the lib would behave how you expect. – Caribou Oct 04 '18 at 12:14

2 Answers2

6

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.

grungegurunge
  • 841
  • 7
  • 13
5

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).

Quentin
  • 62,093
  • 7
  • 131
  • 191