c++ nlohmann::json 中文支持

c++ nlohmann::json 是当前排名第一人库,但是在解析中文时会有问题

std::string to_utf8(std::wstring& wide_string)
{
	static std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
	return utf8_conv.to_bytes(wide_string);
}

void test_nlohmann() {
	using namespace nlohmann;
	nlohmann::json j;

	// 测试中文和英文提前解析
	std::string js1 = R"({"key": "中文"})";
	std::string js2 = R"(Not a json string)";

	std::wstring js3 = LR"({"name":"中文"})";
	std::wstring js4 = LR"("中文"})";

	bool jsonStringIsValid = json::accept(js1);
	bool notJsonStringIsValid = json::accept(js2);

	jsonStringIsValid = json::accept(js3);
	notJsonStringIsValid = json::accept(js4);

	nlohmann::json jt;
	jt["age"] = 1;
	jt["name"] = "张三";

	auto jt_out = jt.dump();
	auto dd = utf8_to_ascii(jt["name"].get<std::string>());

	// 要先转成宽字符
	std::wstring str_json = LR"({"age":"12","name":"中文"})";

	try {
		j = nlohmann::json::parse(str_json);

		auto str_out = j.dump();
		if (j.contains("name") && j["name"].is_string()) {
			std::string value = utf8_to_ascii(j["name"].get<std::string>());
			int c = 0;
		}
	}
	catch (nlohmann::json::parse_error& ex) {
		std::string what = ex.what();
	}

	// 生成带中文的测试
	json j2;
	std::wstring ws = L"中文";

	j2["id"] = 123;
	j2["encoded"] = CW2A(ws.c_str(), CP_UTF8);

	std::string out = j2.dump();

	int c = 0;
}

这样测试成功。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值