关于nlohmann::json的简单使用

nlohmann::json的使用非常简单,只需要包含.hpp文件即可,这是它的官网https://github.com/nlohmann/json
简单使用:

#include "json.hpp"
#include <iostream>

using Info = nlohmann::json;

int main()
{
	Info info;
	std::cout << info.size() << std::endl;
	info["a"] = "b";

	std::cout << info["a"] << std::endl;

	auto iter = info.find("a");
	if (iter == info.end()) {
		std::cout << "not found" << std::endl;
	}
	else {
		std::cout << *iter << std::endl;
	}

	std::string s = R"({
		"name" : "nick",
		"credits" : "123",
		"ranking" : 1
	})";

	auto j = nlohmann::json::parse(s);
	std::cout << j["name"] << std::endl;

	std::string ss = j.dump();
	std::cout << "ss : " << ss << std::endl;

	Info j1;
	Info j2 = nlohmann::json::object();
	Info j3 = nlohmann::json::array();

	std::cout << j1.is_object() << std::endl;
	std::cout << j1.type_name() << std::endl;

	std::cout << j2.is_object() << std::endl;
	std::cout << j2.is_array() << std::endl;

	Info infoo{
		{"name", "darren"},
		{"credits", 123},
		{"ranking", 1}
	};

	std::cout << infoo["name"] << std::endl;

	std::cout << infoo.type_name() << std::endl;

	//遍历
	for (auto iter = infoo.begin(); iter != infoo.end(); iter++) {
		std::cout << iter.key() << " : " << iter.value() << std::endl;
		//std::cout << iter.value() << std::endl;
		//std::cout << *iter << std::endl;
	}

	system("pause");
	return 0;
}

输出:
在这里插入图片描述
最近发现了一个问题,就是它默认会对键进行排序,那如果不想让它排序怎么办?
可以看一下官网的文档
在这里插入图片描述
在这里插入图片描述
可以看到这里说的很详细,这里提供两种方法:

	std::vector<std::pair<std::string, int>> keyValuePairs;
	keyValuePairs.emplace_back("key3", 3);
	keyValuePairs.emplace_back("key1", 1);
	keyValuePairs.emplace_back("key2", 2);

	nlohmann::json jsonObject(keyValuePairs);

	// 输出序列化后的JSON数据
	std::cout << jsonObject.dump() << std::endl;

	std::cout << "===============" << std::endl;
	nlohmann::ordered_json orderjson;
	orderjson["a"] = 1;
	orderjson["c"] = 2;
	orderjson["b"] = 3;

	std::cout << orderjson.dump(2) << std::endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高二的笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值