4

At the moment I am working on a c++ project, writing the server side of an API using the CPPRESTSDK (a.k.a. Casablanca).
Serializing values such as int, double etc. is already implemented in the cpprestsdk library.

I wanted to ask now, if there is any way to serialize a std::vector to a json::value at the client, make a reqeust and then deserialize it at the server?
Something like:

    http_client client(U("http://localhost"));
    json::value jsonVector(std::vector);
    make_task_request(client, methods::POST, jsonVector)

Thank you for everything in advance!

Jahgringo
  • 41
  • 1
  • 2

1 Answers1

2

Vector serialization:

    std::vector<int> someVector;
    web::json::value json;

    std::vector<value> array;

    if (someVectory.size()) {
        for (auto num : someVector) {
            array.push_back(value(num));
        }

        json["yourKey"] = value::array(array);
    }

If you don't need to push the array into a container object, then just use value::array(array) which transforms the std::vector to an array.

To deserialize, let's say you have a known array in array then:

    std::vector<int> intVector;
    for (auto it=array.cbegin();it!=array.cend();++it) {
        intVector.push_back(it->as_integer());
    }
Mobile Ben
  • 7,121
  • 1
  • 27
  • 43
  • 1
    You can also deserialze into a _std::vector_ using its constructor by iterators i.e: _std::vector vec(array.cbegin(), array.cend());_. – Quirysse Aug 23 '17 at 13:15