Jsoncpp用法小结 VS2019

南笙酒味 提交于 2020-01-22 08:30:20


最近工作需要用到JSON解析,使用过程中遇到了几个问题,觉得有必要总结一下

从字符串中解析JSON

    const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
	Json::CharReaderBuilder b;
	Json::CharReader* reader(b.newCharReader());
	Json::Value root;
	JSONCPP_STRING errs;
	bool ok = reader->parse(str, str + strlen(str), &root, &errs);

	std::string upload_id;
	int code = 0;
	if (ok && errs.size() == 0)
	{
		upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"  
		code = root["code"].asInt();    // 访问节点,code = 100  
	}
	else
	{
		cout << "ok=" << ok << ",errs.size()=" << errs.size() << endl;
	}
	delete reader;

从文件中解析JSON


    Json::CharReaderBuilder rbuilder;
	rbuilder["collectComments"] = false;
	Json::Value root_group;
	JSONCPP_STRING errs;
	fstream f;
	f.open("d:\\test.json", ios::in);
	if (!f.is_open())
	{
		cout << "ReadJsonFromFile Open json file error!" << endl;
		return -1;
	}
	bool parse_ok = Json::parseFromStream(rbuilder, f, &root_group, &errs);

	if (!parse_ok)
	{
		cout << "ReadJsonFromFile Parse json file error!" << endl;
		f.close();
		return -1;
	}
	else
	{
		cout << "ReadJsonFromFile success!" << endl;
	}
	f.close();

将JSON写入文件

    Json::Value root_group;
	for (int i = 0; i < 5; ++i) 
	{
		root_group[i]["Age"] = 20;
		root_group[i]["ID"] = i;
	}
	fstream f;
	f.open("d:\\test.json", ios::out | ios::trunc);
	if (!f.is_open())
	{
		cout << "WritrJsonToFile Open file error!" << endl;
		return -1;
	}
	f << root_group.toStyledString(); 
	f.close();

输出JSON字符串

官网只提供了toStyledString()这个方法输出字符串,对于不需要格式化输出字符需要自己写代码。toStyledString()的源码如下:

    String Value::toStyledString() const {
		StreamWriterBuilder builder;

		String out = this->hasComment(commentBefore) ? "\n" : "";
		out += Json::writeString(builder, *this);
		out += '\n';

		return out;
	}

查看了 StreamWriterBuilder的源码,默认设置为以"\t"格式化输出JSON。并且StreamWriterBuilder提供设置格式化的方法。在toStyledString() 的基础上新增了toString() 方法,源码如下:

    String Value::toString() const {
		StreamWriterBuilder builder;
		builder.settings_["indentation"] = ""; //设置格式化字符串为空格
		String out = this->hasComment(commentBefore) ? "\n" : "";
		out += Json::writeString(builder, *this);
		//out += '\n';//去掉最后的换行符
		return out;
	}

另外JSONCPP默认编码是UTF8,与VS默认编码不一致,当输入中文时会出现乱码,StreamWriterBuilder提供设置默认编码的参数,重载toString(),代码如下:

	String Value::toString(const bool emitUTF8) const {
		StreamWriterBuilder builder;
		builder.settings_["indentation"] = ""; //不格式化输出开始
		builder.settings_["emitUTF8"] = emitUTF8; //非UTF8编码填true
		String out = this->hasComment(commentBefore) ? "\n" : "";
		out += Json::writeString(builder, *this);
		return out;
	}

重载toStyledString() ,代码如下

    String Value::toStyledString(const bool emitUTF8) const {
		StreamWriterBuilder builder;
		builder.settings_["emitUTF8"] = emitUTF8; //非UTF8编码填true
		String out = this->hasComment(commentBefore) ? "\n" : "";
		out += Json::writeString(builder, *this);
		out += '\n';

		return out;
	}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!