基本Json格式化。
This commit is contained in:
45
formater/fmt.json.cpp
Normal file
45
formater/fmt.json.cpp
Normal file
@@ -0,0 +1,45 @@
|
||||
#include "fmt.json.h"
|
||||
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
JsonFormatter::JsonFormatter()
|
||||
{
|
||||
}
|
||||
|
||||
std::string JsonFormatter::format(const std::string& path, const FormatterArg& arg)
|
||||
{
|
||||
std::string result;
|
||||
boost::nowide::ifstream ifs(path);
|
||||
if (!ifs.is_open())
|
||||
return "";
|
||||
std::string content((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
|
||||
// std::cout << "Content: " << content << std::endl;
|
||||
|
||||
formatContent(content, arg, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool JsonFormatter::formatContent(const std::string& content, const FormatterArg& arg, std::string& outContent)
|
||||
{
|
||||
try {
|
||||
json j = json::parse(content);
|
||||
outContent = j.dump(arg.indent);
|
||||
return true;
|
||||
} catch (json::parse_error& e) {
|
||||
AxcUtil::getLogger()->error("Parse json content error: [{}], return default content.", e.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool JsonFormatter::save(const std::string& path, const std::string& content)
|
||||
{
|
||||
boost::nowide::ofstream ofs(path);
|
||||
if (!ofs.is_open())
|
||||
return false;
|
||||
ofs << content;
|
||||
return true;
|
||||
}
|
||||
22
formater/fmt.json.h
Normal file
22
formater/fmt.json.h
Normal file
@@ -0,0 +1,22 @@
|
||||
#ifndef FMT_JSON_H
|
||||
#define FMT_JSON_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "util/axc.util.h"
|
||||
|
||||
class JsonFormatter
|
||||
{
|
||||
public:
|
||||
JsonFormatter();
|
||||
|
||||
public:
|
||||
std::string format(const std::string& path, const FormatterArg& arg);
|
||||
bool formatContent(const std::string& content, const FormatterArg& arg, std::string& outContent);
|
||||
bool save(const std::string& path, const std::string& content);
|
||||
|
||||
private:
|
||||
std::shared_ptr<spdlog::logger> logger;
|
||||
};
|
||||
|
||||
#endif // FMT_JSON_H
|
||||
Reference in New Issue
Block a user