Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::vector to JSON using CPPREST-SDK

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!

like image 215
Jahgringo Avatar asked Oct 24 '25 03:10

Jahgringo


1 Answers

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());
    }
like image 180
Mobile Ben Avatar answered Oct 25 '25 18:10

Mobile Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!