用jsoncpp 开源库, 解析json文件

转载地址:

https://blog.csdn.net/yc461515457/article/details/52749575

https://blog.csdn.net/u012372584/article/details/78901015

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。通常用于数据交换或存储。

JsonCpp是一个基于C++语言的开源库,用于C++程序的Json数据的读写操作。

JsonCpp是一个开源库

下载地址:https://github.com/open-source-parsers/jsoncpp

文档地址:http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

使用

官方提供的集成方案:https://github.com/open-source-parsers/jsoncpp/wiki/Amalgamated

其中最简单的方法是执行项目根目录中的python脚本,构建头文件和源文件。

1. 在安装Python环境的控制台中进入jsoncpp项目根目录,

2. 执行命令:

python amalgamate.py

3. 将生成的dist目录拷贝到自己的项目中,其中包源文件jsoncpp.cpp和头文件json.h、json-forwards.h

基本类和方法

使用jsoncpp库时需要包含头文件#include <json/json.h>(包含目录根据需要修改)

方法命名空间:Json

jsoncpp中主要的类:

Json::Value:可以表示所有支持的类型,如:int , double ,string , object, array等。其包含节点的类型判断(isNull,isBool,isInt,isArray,isMember,isValidIndex等),类型获取(type),类型转换(asInt,asString等),节点获取(get,[]),节点比较(重载<,<=,>,>=,==,!=),节点操作(compare,swap,removeMember,removeindex,append等)等函数。

Json::Reader:将文件流或字符串创解析到Json::Value中,主要使用parse函数。Json::Reader的构造函数还允许用户使用特性Features来自定义Json的严格等级。

Json::Writer:与JsonReader相反,将Json::Value转换成字符串流等,Writer类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter(将数据写入一行,没有格式),Json::StyledWriter(按json格式化输出,易于阅读)。

Json::Reader可以通过对Json源目标进行解析,得到一个解析好了的Json::Value,通常字符串或者文件输入流可以作为源目标。


比如in.json文件为:

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],
    "indent" : { "length" : 3, "use_space": true },

"tab-length":[],

"tab":null
}

基本用法:

#include <json.h>
#include <fstream>
#include <iostream>

int createJSON(){
Json::Value root;
root["Result"] = 1;
root["ResultMessage"] = "200";

Json::Value object1;
object1["cpuRatio"] = "4.04";
object1["serverIp"] = "42.159.116.104";
object1["conNum"] = "1";
object1["websocketPort"] = "0";
object1["mqttPort"] = "8883";
object1["TS"] = "1504665880572";

Json::Value object2;
object2["cpuRatio"] = "2.04";
object2["serverIp"] = "42.159.122.251";
object2["conNum"] = "2";
object2["websocketPort"] = "0";
object2["mqttPort"] = "8883";
object2["TS"] = "1504665896981";

Json::Value jarray;
jarray.append(object1);
jarray.append(object2);

root["ResultValue"] = jarray;

Json::StyledWriter  swriter;
std::string jsonstr = swriter.write(root);
std::ofstream  out("create.json");
out << jsonstr;
out.close();

return 0;
}


int main(int argc, char* argv[]) {

	Json::Reader reader;
	Json::Value root;
	Json::FastWriter fwriter;
	Json::StyledWriter swriter;


	const char* s = "in.json";
	std::ifstream  infile;
	infile.open(s);
	// 或者直接 std::ifstream infile(s);

	if (!infile.is_open()) {
		std::cerr << "could not open file: " << *s << std::endl;
		return -1;
	}
		
	if (reader.parse(infile, root)) {
		Json::Value  temp;

		temp = root["encoding"];
		std::cout << temp.asString()<< std::endl << std::endl;

		temp = root["plug-ins"];
		int size = temp.size();
		for (int i = 0; i < size; i++) {		  
			std::cout << temp[i].asString()<<std::endl<<std::endl;
		}

		temp = root["indent"];
		std::cout << temp["length"].asInt() << std::endl << std::endl;
		std::cout << temp["use_space"].asBool() << std::endl << std::endl;	
	}
	infile.close();
	

	std::ofstream outfile;
	outfile.open("out_fast.json");  //没有的话,创建,打开; 否则,清空其内容,打开
	//std::ofstream  outfile("out.json"); 

	std::string str = fwriter.write(root);
	outfile << str << std::endl << std::endl;
	outfile.close();

	str = swriter.write(root);
	outfile.open("out_style.json");
	outfile << str << std::endl << std::endl;
	outfile.close();


	if (root.isMember("encoding"))
		std::cout << "encoding existed" << std::endl;
	if (!root.isMember("enco"))
		std::cout << "enco not exist!!" << std::endl;

	if (root["tab"].isNull()) 
		std::cout << "tab isNull" << std::endl;//print isNull
		
	if (root.isMember("tab-length")) {//true
		if (root["tab-length"].isNull()) 
		      std::cout << "tab-length isNull" << std::endl;		
		else std::cout << "tab-length not Null" << std::endl;
		// print "tab-length not Null", there is a array object([]), through this array object is empty
		std::cout << "empty: " << root["tab-length"].empty() << std::endl;//print empty: 1
		std::cout << "size: " << root["tab-length"].size() << std::endl;//print size: 0
	}

	bool flag = root["anything-not-exist"].asBool();//false
	std::cout << "flag: " << flag<<std::endl;
	flag=root.isMember("anything-not-exist"); //true
	std::cout << "flag: " << flag<<std::endl;

	//typedef std::vector<std::string> Json::Value::Members
	Json::Value::Members  key_list = root.getMemberNames();

	root.removeMember("encoding");

	system("pause");

	createJSON();

	return 0;

}
最后生成的create.json为:
{
   "Result" : 1,
   "ResultMessage" : "200",
   "ResultValue" : [
      {
         "TS" : "1504665880572",
         "conNum" : "1",
         "cpuRatio" : "4.04",
         "mqttPort" : "8883",
         "serverIp" : "42.159.116.104",
         "websocketPort" : "0"
      },
      {
         "TS" : "1504665896981",
         "conNum" : "2",
         "cpuRatio" : "2.04",
         "mqttPort" : "8883",
         "serverIp" : "42.159.122.251",
         "websocketPort" : "0"
      }
   ]
}

其他操作:

《1》判断Key值是否存在

bool Json::Value::isMember (constchar * key)const
bool Json::Value::isMember (const std::string & key)const
bool Json::Value::isMember (constchar*key,constchar * end ) const

《2》判断value是否为NULL
bool Json::Value::isNull ( ) const

《3》另外值得强调的是,Json::Value和C++中的map有一个共同的特点,就是当你尝试访问一个不存在的 key 时,会自动生成这样一个key-value默认为null的值对。也就是说解析时,先判断key是否存在,然后判断value是否为null,再根据类型取值

bool flag = root["anything-not-exist"].asBool();//false
std::cout << "flag: " << flag<<std::endl;
flag=root.isMember("anything-not-exist"); //true
std::cout << "flag: " << flag<<std::endl;
《4》获取所有的key

//typedef std::vector<std::string> Json::Value::Members
Json::Value::Members  key_list = root.getMemberNames();

《5》删除成员

root.removeMember("encoding");




猜你喜欢

转载自blog.csdn.net/u011722133/article/details/80187929