Jsoncpp用法小结 VS2019

Jsoncpp用法小结 VS2019


最近工作需要用到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;
	}
Jsoncpp用法小结 VS2019Jsoncpp用法小结 VS2019 qq_360917936 发布了1 篇原创文章 · 获赞 1 · 访问量 21 私信 关注
上一篇:arm linux添加自启动脚本


下一篇:Docker 安装和 Flask项目部署