矢量类型为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);
那么,我如何将这个矢量保存在计算机上,然后在需要时重读,并将文件再次转换为同一矢量?
我使用了nlohmann JSON。你可以在这里找到它->https://json.nlohmann.me/
我的代码:
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
}
JSON文件的输出应该如下所示:
{
"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"
}
]
}
你可以在他们的网站上找到有用的例子:https://json.nlohmann.me/api/basic_json/#non-成员功能
我希望你能找到一个有用的答案:D