Search code examples
jsonstlcpprest-sdk

JSON serialize std::list and std::map using cpprestsdk


I am using cpprestsdk to write a server application in C++ that uses REST services. In my application, I have to serialize a class that contains std::list and std::map objects to JSON.

Is there any example on serialize STL classes using cpprestsdk(https://github.com/Microsoft/cpprestsdk/)


Solution

  • You can serialize std::list and std::map as JSON arrays. One example for std::map is

    void mapToJson()
    {
        web::json::value result = web::json::value::array();
        std::map<int, utility::string_t> m;
    
        int i = 0;
        for each (std::pair<int, utility::string_t> p in m)
        {
            web::json::value obj = web::json::value::object();
    
            obj[U("integer")] = web::json::value(p.first);
            obj[U("string")] = web::json::value(p.second);
    
            result[i++] = obj;
        }
    }