json读写(简洁版,不依赖第三方库)

网上很多教材很全面的介绍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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值