[C++] C++ operation jsoncpp (write, read, parse) + jsoncpp configuration steps from 0 to 1

foreword

The json file is a relatively lightweight file with a simple format and easy to use. Compared with other methods for storing information, it has its own unique advantages.

What I will share with you today is how to use C++ to manipulate json files.

If you know how to use the jsoncpp class library, you don’t need to read the appendix. If you are using it for the first time, please go to the end first, configure the environment, and then proceed.

01. Introduction to json files

1.1 Introduction to json

JSON (JavaScript Object Notation, JS Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (the js specification developed by the European Computer Association), and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clear hierarchy make JSON an ideal data interchange language. It is easy for people to read and write, and it is also easy for machines to parse and generate, and it can effectively improve the efficiency of network transmission .

1.2. Advantages of json

There are many ways to store data commonly used, such as using txt files, xml files, word files, Excel files, and if our requirements are relatively high, we can also use database files ( / MySQL/ SQL Server) Oracle.

  1. Compared with txt and word, the json format is more clear, and it is very convenient to obtain important information.
  2. Compared with xml, the json format is more concise, storing the same file requires less memory.
  3. Compared with Excel, json is more suitable for storing character files. Excel is equivalent to a relatively simple database.
  4. Compared with the database, json is more convenient, and we need to do some settings and install some software for the database. json can be used directly.

02. C++ operation jsoncpp (read, write, parse)

I write all the function calls in the program in the final Main.cpp, and the declarations and definitions that appear below are the split versions of the contents in OperationJson.h and OperationJson.cpp.

2.1, analysis (nor)

Before parsing, we first define a simple string (intermediate string) to replace the parsing in json format, as follows:

/* Json格式 */
{
    
    
	"name":"Cain",
	"age":23,
	"sex":"man"
}
/* 字符串格式 */
const char* str = "{\
					\"name\":\"Cain\",\
					\"age\":23,\
					\"sex\":\"man\"\
					}";

String format parsing: (The boss can skip it by himself, and the novice will explain it)

  1. "{\: This \means that the next line starts after this line, and does not end.
  2. \"name\”: Here \", it represents the escaping of strings, the basics of C language, if you forget, you can review it.
  3. All value formats in json are identified by the beginning and end. What do you mean, that is, if you \"age\":23write this here, it is an in type, which will be used later asIng(), parsed, and the same is true internally , if you \"age\":\"23\"
    write in this way, internally identify the beginning and end “”, and use it asString()for parsing, and what you want asInt(), an assertion error will occur, because the error handling methods in jsoncpp are all assertions . Here is the pit I stepped on. Let me explain it and share it with you. In the following examples, I will not repeat it.

Kernel Code:

#include <string>

//声明
void AnalysisJsonString(string strJsonText);

//定义  (实际我是以类的形式对这三种写法写的代码,这只是我拆分出来方便大家看)
void OperJson::AnalysisJsonString(string strJsonText)
{
    
    
	string name,sex;
	int age;
	
	Json::Reader reader;
	Json::Value value;

	//从字符串中读取数据
	if(reader.parse(strJsonText,value))
	{
    
    
		name = value["name"].asString();
		age = value["age"].asInt();
		sex = value["sex"].asString();
	}

	//输出格式大家自定义就好了,我这么写完全是为了输出好看
	cout << "{ " << endl;
	cout << "   " << "\"name\":" << " \" " << name << " \" " <<endl;
	cout << "   " << "\"age\":" << age<<endl;
	cout << "   " << "\"sex\":" << " \" " << sex<< " \" " <<endl;
	cout << "} " << endl;
}

Run Image:
insert image description here

2.2. Analysis (pro)

Or first define a string (a bit more complicated), as follows:

//Json格式
{
    
    
	"name":"Cain",
	"major":
	[
	{
    
     "computer" : "C"},
	{
    
     "computer" : "C++"},
	{
    
     "computer" : "Python"},
	{
    
     "computer" : "Go"}
	]
}

//字符串格式
const char* buf = "{\
					\"name\":\"Cain\",\
					\"major"\:[{
    
    \
					\"computer\":\"C\"},\
					\"computer\":\"C++\"},\
					\"computer\":\"Python\"},\
					\"computer\":\"Go\"}\
					]}";

String parsing (omitted).

Kernel Code:

//声明
void AnalysisJsonStringPro(string strJsonText);

//定义
void OperJson::AnalysisJsonStringPro(string strJsonText)
{
    
    
	string name;
	string major;
	vector<string> vec;  //包含vector头文件
	
	Json::Reader reader;
	Json::Value value;
	Json::Value root;
	
	if(reader.parse(strJsonText,root))
	{
    
    
		name = root["name"].asString();
		value = root["major"];
		cout << "name: " << name << endl;
		
		for(int i = 0; i < root["major"].size(); i++)
		{
    
    
			major = value[i]["computer"].asString();
			vec.push_back(major);
		}
	}
	//区间迭代(C++ 11)
	for(string buf : vec)
	{
    
    
		cout << "major: " << buf << endl;
	}
}

Regarding interval iteration, if you are interested, you can check out an STL blog I wrote before [STL] standard container-vector .

Run Image:
insert image description here

2.3, write Json file

When reading and writing Json files, I will directly upload the code + test diagram. If you are interested, you can take it and test it yourself. The program must be OK.

Kernel Code:

//声明
void WriteFileJson(string filePath);

//定义
void OperJson::WriteFileJson(string filePath)
{
    
    
	//写入下列指定内容
	const char* str = "{\
						\"name\":\"Cain\",\
						\"sex\":\"man\",\
						\"age\":23,\
						\"hobby\":[\"Run\",\"Sing\",\"Dance\"],\
						\"major\":[\
						{\"subject1\":\"C++\"},\
						{\"subject2\":\"Jave\"},\
						{\"subject3\":\"Go\"}]\
						}";

	Json::Value root;
	root["name"] = Json::Value("Cain");
	root["sex"] = Json::Value("man");
	root["age"] = Json::Value(23);
	
	//数组形式
	root["hobby"].append("Run");
	root["hobby"].append("Sing");
	root["hobby"].append("Dance");
	
	Json::Value Sub;
	//子节点属性
	Sub["subject1"] = Json::Value("C++");
	Sub["subject2"] = Json::Value("Java");
	Sub["subject3"] = Json::Value("Go");

	//将子节点内容挂到父节点(root)上
	root["major"] = Json::Value(Sub);

	/* 测试内容:会在屏幕输出 */
	cout << "styledwriter: " << endl;
	Json::StyledWriter sw;
	cout << sw.write(root) << endl;

	//将内容输入到指定的文件
	ofstream os;
	os.open(filePath,ios::out || iios::app);
	if(!os.is_open())
	{
    
    
		cout << "Error: can not find or create the file which named " << filePath << endl;
	}
	else
	{
    
    
		cout << "successful: file write is success! " << endl;
	}

	os << sw.write(root);
	os.close();
}

Run Image:
insert image description here
insert image description here

2.4, read Json file

Kernel Code:

//声明
void ReadFileJson(string filePath);

//定义
void OperJson::ReadFileJson(string filePath)
{
    
    
	Json::Reader reader;
	Json::Value root;
	
	//读取文件中的数据
	ifstream in;
	in.open(filePath,ios::in || ios:: binary);
	if(!in.is_open())
	{
    
    
		cout << "Error: open file is failed! " << endl;
	}
	else
	{
    
    
		cout << "Successful: file read is success! " << endl;
	}
	
	Json::StyledWriter sw;

	if(reader.parse(in,root))
	{
    
    
		//读取节点信息
		string name = root["name"].asString();
		int age = root["age"].asInt();
		string sex = root["sex"].asString();
		
		for(int i = 0; i < root["hobby"].size(); i++)
		{
    
    
			string str = root["hobby"][i].asString();
		}

		Json::Value tmp;
		tmp = root["major"];

		sw write(root);
		cout << sw.write(root) << endl;
	}
	else
	{
    
    
		cout << "Error: parse is error! " << endl;
	}
}

Run Image:
insert image description here

2.5、Main.cpp

#include <iostream>
#include <string>
#include "OperationJson.h"

using namespace std;

/* 定义两个宏,使读写json文件区分开来,当然也可以只用一个,读写都用一个,最简单 */
#define READ_JSONFILE_PATH "C:\\Users\\M\\Desktop\\read.json"
#define WRITE_JSONFILE_PATH "C:\\Users\\M\\Desktop\\write.json"

int maiin(int argc,char* argv[])
{
    
    
	const char* str = "{\
					\"name\":\"Cain\",\
					\"age\":23,\
					\"sex\":\"man\"\
					}";
					
	const char* buf = "{\
					\"name\":\"Cain\",\
					\"major"\:[{
    
    \
					\"computer\":\"C\"},\
					\"computer\":\"C++\"},\
					\"computer\":\"Python\"},\
					\"computer\":\"Go\"}\
					]}";

	OperJson json;

	//简单解析Json(字符串形式)
	json.AnalysisJsonString(str);
	//升级版解析Json(字符串形式)
	json.AnalysisJsonString(buf);
	//写Json文件
	json.WriteFileJson(WRITE_JSONFILE_PATH);
	//读Json文件
	json.ReadFileJson(READ_JSONFILE_PATH);

	system("pause");
	return 0;
}

Ps: If you write two macros as I did above, then the json file is either created externally, or written first and then renamed. Because actually when we use json files, they do not have the same name. Of course, it is definitely easier to use the same name for testing. You can decide for yourself.
The above involves the reading and writing method in iostream.hthe header file. This is the method in C++, which is the same as the principle of C. You can learn about it online.
Note:
1. If the file to be written does not exist, it will be created automatically;
2. If the file exists, the writing process will not overwrite the original data in the file, but will write the new data behind the original data.

03. Jsoncpp library configuration from 0 to 1

JsonCpp is an open source library based on C++ language, used for reading and writing Json data of C++ programs.

3.1, Jsoncpp library download

Jsoncpp library github address: https://github.com/open-source-parsers/jsoncpp
Jsoncpp document address: http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html
jsoncpp official website library Address: https://sourceforge.net/projects/jsoncpp/

I am using the library package downloaded from the third link, and the configuration below is the same. Taking the third one as an example, the core steps are the same, so don’t worry about the download address being different and making it unusable.

3.2. Configuration steps

  • Unzip and transfer
    First unzip the library, copy the following two folders to the project you created, as shown below:
    insert image description here
    insert image description here

  • Project configuration
    First enter your VS project, click on the item on the toolbar --> properties , and then follow the steps below:

insert image description here

  • Jsoncpp header file usage

    Copy all the files under the include folder just now and all the files under the json folder under src to the new filter item in the project directory (just add and create a new filter item directly in the VS interface), as shown belowinsert image description here
    insert image description here

Configured here, the Jsoncpp library can be used in the project.

04. Appendix

Regarding the use, if you do not manually create the file when writing the file, it cannot be created iostream.haccording to the above code. ofstream os(文件路径);file will do just fine.

The github address connected to the jsoncpp configuration refers to the reference in the following article:
https://www.cnblogs.com/esCharacter/p/7657676.html

Copyright Statement: Creation is not easy, please indicate the source for reprinting!

Guess you like

Origin blog.csdn.net/m0_43458204/article/details/116755032