我第一次使用https://github.com/nlohmann/json,我必须像这样创建文件层次结构:
{
"Files": [
{
"Name": "Test.txt",
"Size": "27 B",
"Path": "D:\\Projects\\Test.txt"
},
...
],
"Children": [
{
"Name": "SubProjects",
"Files": [
{
"Name": "SubTest.txt",
"Size": "2 B",
"Path": "D:\\Projects\\SubProjects\\SubTest.txt"
},
...
],
"Children": [
....
]
},
{
"Name": "SubProjects3",
"Files": [],
"Children": []
},
...
]}
现在我在嵌套节点中添加信息时遇到问题。我试图通过搜索新键“级别”来解决这个问题,并试图找到这个键等于我需要的级别,但它仍然不起作用。我的代码:
#include <iostream>
#include <conio.h>
#include <nlohmann/json.hpp>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <experimental/filesystem>
using namespace std;
using json = nlohmann::json;
namespace fs = std::experimental::filesystem;
void DisplayFileInfo(const fs::v1::directory_entry& entry, fs::v1::path& filename , json &j_main,int level)
{
json j_file;
j_file["Name"] = filename.string();
j_file["Size"] = fs::file_size(entry);
j_file["Path"] = fs::absolute(filename).string();
for ( auto& obj : j_main) {
if (obj["Level"] == level) {
obj["Files"].push_back(j_file);
}
}
}
void DisplayFolderInfo(const fs::v1::directory_entry& entry, fs::v1::path& filename, json &j_main, int level)
{
json j_folder;
j_folder["Level"] = level+1;
j_folder["Name"] = filename.string();
j_folder["Files"] = json::array({});
j_folder["Children"] = json::array({});
for (auto& obj : j_main)
{
if (obj["Level"] == level) {
obj["Children"].push_back(j_folder);
}
}
void DisplayDirectoryTree(const fs::path& pathToShow, int level, json &j_main)
{
if (fs::exists(pathToShow) && fs::is_directory(pathToShow))
{
for (const auto& entry : fs::directory_iterator(pathToShow))
{
auto filename = entry.path().filename();
if (fs::is_directory(entry.status()))
{
DisplayFolderInfo(entry, filename,j_main,level);
level++;
DisplayDirectoryTree(entry,level,j_main);
}
else if (fs::is_regular_file(entry.status()))
DisplayFileInfo(entry, filename,j_main,level);
}
}
}
int main()
{
char folder_path[255];
cout << "Please input name of folder with full path: " << endl;
cin >> folder_path;
json j_main;
j_main["Level"] = 0;
j_main["Children"] = json::array({});
j_main["Files"] = json::array({});
const fs::path pathToShow=folder_path;
DisplayDirectoryTree(pathToShow, 0,j_main);
ofstream o("file.json");
o << setw(4) << j_main << endl;
_getch();
return 0;
}