Search code examples
c++savestdvector

How to save a vector of a custom type of elements on disk, read it, and parse it into a vector again using C++


The vector type is TrackInfo:

class TrackInfo
{
public:
    TrackInfo(URL& _url, String& _title, double& _length, String _fileFormat);

    URL url;
    String title;
    double length;
    String fileFormat;
};


====================================================================================

std::vector<TrackInfo> tracks;
TrackInfo track(fileURL, fileName, length, fileFormat);
tracks.push_back(track);
tracks.push_back(track);

So, how can I save this vector on the computer and then reread it when I need and convert the file into the same vector again?


Solution

  • I used nlohmann JSON. You can find it here -> https://json.nlohmann.me/

    My code:

    std::vector<TrackInfo> StoreData::jsonToTrackInfo(json jsonFile)
    {
        std::vector<TrackInfo> tracks;
    
        for (json jsonf : jsonFile["Playlist"])
        {
            // Try to parse the data. If there is an error, return the empty vector.
            // If one of the Playlist tracks has a problem, it won't be parsed and will parse the rest of the playlist.
            try
            {
                String urlString = jsonf["url"];
                String title     = jsonf["title"];
                double length    = jsonf["length"];
                String format    = jsonf["format"];
                URL url { urlString };
    
                TrackInfo track(url, title, length, format);
                tracks.push_back(track);
            }
            catch (const std::exception&)
            {
                //..
            }
        }
        return tracks;
    }
    
    json StoreData::trackInfoToJson(std::vector<TrackInfo> tracks)
    {
        json j;
    
        // Convert each track into JSON data.
        for (TrackInfo track : tracks)
        {
            j.push_back(
                {
                    {"url"  , track.url.toString(false).toStdString()},
                    {"title" , track.title.toStdString() },
                    {"length", track.length},
                    {"format", track.fileFormat.toStdString()}
                }
            );
        }
    
        json jsonFile;
        jsonFile["Playlist"] = j;   
    
        return jsonFile; // return the Json File
    }
    

    and the output of the JSON file should look like this:

    {
        "Playlist": [
            {
                "format": ".mp3",
                "length": 106.0,
                "title": "c_major_theme.mp3",
                "url": "file:///C%3A/Users/me/Desktop/tracks/c_major_theme.mp3"
            },
            {
                "format": ".mp3",
                "length": 84.0,
                "title": "fast_melody_regular_drums.mp3",
                "url": "file:///C%3A/Users/me/Desktop/tracks/fast_melody_regular_drums.mp3"
            }
        ]
    }
    

    You can find helpful examples here on their website: https://json.nlohmann.me/api/basic_json/#non-member-functions

    I hope you find this a helpful answer :D