网上很多教材很全面的介绍json,本例主要是记录如何快速运用json到项目去,基于S10缺陷检测主要基于模板匹配,所以需要提前准备好模型及检测框等,代码每次读取很是麻烦,后期调试也是繁琐,故把预存的数据统一写成json配置文件的形式来读取,增强代码的可阅读性及简化重复调试。
#include <iostream>
#include <fstream>
#include <iomanip>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
int main()
{
cout << "Json test" << endl;
//**********************************************json初始化**********************************************//
//第一种方法 字符串转json
string strValue = "{\"name\":\"shuiyixin\",\"major\":[{\"AI\":\"MachineLearning\"},{\"AI\":\"DeepLearning\"},{\"AI\":\"ComputerVision\"}]}";
json j1 = "{\"name\":\"shuiyixin\",\"major\":[{\"AI\":\"MachineLearning\"},{\"AI\":\"DeepLearning\"},{\"AI\":\"ComputerVision\"}]}"_json;
//第一种方法 直接按key-value赋值
json j;
// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean that is stored as bool
j["happy"] = true;
// add a string that is stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
// add an object inside the object
j["answer"]["everything"] = 42;
// add an array that is stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };
// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };
//**********************************************json保存**********************************************//
cout << strValue << endl;
string s = "xdfile.json";
ofstream outFile(s);
outFile << setw(4) << j << endl;
//**********************************************json获取**********************************************//
ifstream inFile(s);
json i;
inFile >> i;
cout << "Json i[name]:" << i["object"]["value"] <<endl;
return 0;
}