json库 nlohmann/json 的基本使用

C++的json库有很多。但nlohmann(链接:https://github.com/nlohmann/json)大概是目前使用最方便的跨平台json库了,其可以让用户以modern C++的方式解析和构建json。性能比rapidjson库略低,但是api比apidjson好用多了。本文讲述nlohmann json库的基本使用。

准备工作:

在visual studio里面设置附加包含目录,把nlohmann json的头文件路径添加进去

例子1:解析std::string里面的json内容并打印到控制台

#include <fstream>
#include <iostream>
#include "nlohmann/json.hpp"

using namespace std;
using json = nlohmann::json;


int main()
{
	string strJson = "{ \"actioncode\":\"user_splicer_screen_info_rsp\", \"Result\" : 200, \"data\" : {\"BigScreenInfos\": [{\"Dpix\":1920, \"Dpiy\" : 1080}, {\"Dpix\": 640,\"Dpiy\" : 480}] } }";
	cout << strJson << endl;

	try {
		json j = json::parse(strJson);
		if (j.contains("actioncode"))
		{
			string strActionCode = j["actioncode"];
			cout << "actioncode: " << strActionCode << endl;
		}
		if (j.contains("Result"))
		{
			int nResult = j["Result"];
			cout << "Result: " << nResult << endl;
		}
		if (j.contains("data"))
		{
			json jData = j["data"];
			if (jData.contains("BigScreenInfos"))
			{
				json jBigScreenInfos = jData["BigScreenInfos"];
				for (auto const& e : jBigScreenInfos)
				{
					if (e.contains("Dpix"))
					{
						int nDpix = e["Dpix"];
						cout << "Dpix: " << nDpix;
					}
					if (e.contains("Dpiy"))
					{
						int nDpiy = e["Dpiy"];
						cout << " Dpiy: " << nDpiy << endl;
					}
				}
			}
		}
	}

	catch (json::parse_error& e)
	{
		cerr << "Error in " << __FILE__ << ":" << __LINE__ << " (function " << __FUNCTION__ << ") - " << e.what() << endl;
	}
	catch (json::exception& e)
    {
		 cerr << "Error in " << __FILE__ << ":" << __LINE__ << " (function " << __FUNCTION__ << ") - " << e.what() << endl;
    }
	return 0;
}

如果解析失败,比如要解析的json格式不正确,会进入catch (json::parse_error& ex)代码段里面,打印错误提示。

运行效果:

例子2:读取并解析json配置文件(input.json)里面的内容,打印到控制台

#include <fstream>
#include <iostream>
#include "nlohmann/json.hpp"

using namespace std;
using json = nlohmann::json;


int main()
{
	string strFileName = "input.json";
	std::ifstream f(strFileName);
	if (!f.good())
	{
		cerr << "open " << strFileName << " failed" << endl;
		return 0;
	}
	try {
		json j = json::parse(f);
		if (j.contains("actioncode"))
		{
			string strActionCode = j["actioncode"];
			cout << "actioncode: " << strActionCode << endl;
		}
		if (j.contains("Result"))
		{
			int nResult = j["Result"];
			cout << "Result: " << nResult << endl;
		}
		if (j.contains("data"))
		{
			json jData = j["data"];
			if (jData.contains("BigScreenInfos"))
			{
				json jBigScreenInfos = jData["BigScreenInfos"];
				for (auto const& e : jBigScreenInfos)
				{
					if (e.contains("Dpix"))
					{
						int nDpix = e["Dpix"];
						cout << "Dpix: " << nDpix;
					}
					if (e.contains("Dpiy"))
					{
						int nDpiy = e["Dpiy"];
						cout << " Dpiy: " << nDpiy << endl;
					}
				}
			}
		}
	}

	catch (json::parse_error& e)
	{
		cerr << "Error in " << __FILE__ << ":" << __LINE__ << " (function " << __FUNCTION__ << ") - " << e.what() << endl;
	}
	catch (json::exception& e)
	{
		cerr << "Error in " << __FILE__ << ":" << __LINE__ << " (function " << __FUNCTION__ << ") - " << e.what() << endl;
	}
	return 0;
}

要被解析的json文件内容如下:

{
	"actioncode": "user_splicer_screen_info_rsp",
	"Result": 200,
	"data": {
		"BigScreenInfos": [{
				"Dpix": 1920,
				"Dpiy": 1080
			},
			{
				"Dpix": 640,
				"Dpiy": 480
			}
		]
	}
}

运行效果:

例子3:构建json字符串,打印到控制台,并保存为json配置文件(output.json)

#include <fstream>
#include <iostream>
#include "nlohmann/json.hpp"

using namespace std;
using json = nlohmann::json;


int main()
{
    json j = json::object();
    j["actioncode"] = "user_splicer_screen_info_rsp";
    j["Result"] = 200;
    auto arrBigScreenInfos = json::array();
    arrBigScreenInfos.push_back([]{
        auto obj = json::object();
        obj["Dpix"] = 1920;
        obj["Dpiy"] = 1080;
        return obj;
        }());
    arrBigScreenInfos.push_back([] {
        auto obj = json::object();
        obj["Dpix"] = 640;
        obj["Dpiy"] = 480;
        return obj;
        }());
    j["data"]["BigScreenInfos"] = arrBigScreenInfos;
    string strjson = j.dump();
    cout << strjson << endl;
    
    std::ofstream outfile("output.json");
    outfile << j << endl;
	return 0;
}

运行效果:

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值