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;
}

这样测试成功。