Introduction and use of 382 Jason

Posted by jmaker on Sat, 01 Jan 2022 14:44:02 +0100

Introduction and use of Jason

Json is a lightweight data exchange format (also known as data serialization). Json uses a text format completely independent of the programming language to store and represent data. The concise and clear hierarchy makes Json an ideal data exchange language. It is easy for people to read and write, easy for machine analysis and generation, and effectively improves the network transmission efficiency.

When we are working on the chat server project, for example, we send a chat message. There are many kinds of messages. Use msg_type: login messages, registration messages, chat messages, or messages of adding friends and groups. from where, to whom, and the content of the msg message.

msg_type:2
from:xxx
to:xxx
msg:xxx

It is roughly the above structure, but we send byte streams through network TCP. Therefore, for such message structures, we need to serialize data (convert it into json byte stream and send it to the network) and deserialize data (the remote end receives the byte stream, reports it to the application, and the application deserializes the json byte stream into such a message structure).

There are many xml node elements and tags, which wastes space. Now protobuf and json are used more.

An excellent Jason tripartite Library

JSON for Modern C + + is a JSON library written by German Daniel nlohmann and used in C + +.
It has the following characteristics
1. Intuitive syntax
2. The whole code consists of a header file, JSON HPP, without subprojects, dependencies, and complex build systems, is very convenient to use
3. Written in C++ 11 standard
4. Using json is like using an STL container
5. STL and json containers can be converted to each other
6. Rigorous testing: all classes have undergone strict unit testing, covering 100% of the code, including all special behaviors. In addition, Valgrind was checked for memory leaks. In order to maintain high quality, the project follows the best practices of the core infrastructure Initiative (CII)

Contains json header files

In the network, the commonly used data transmission serialization formats are XML, Jason and ProtoBuf. In company level projects, a large number of people use ProtoBuf as data serialization, which uses its data compression coding transmission and occupies a small bandwidth. The same data information is 1 / 10 of that of Jason and 1 / 20 of that of XML, but it is a little more complex than that of Jason.
In the project of distributed TCP network communication framework based on RPC service, I use the serialization and deserialization of protobuf. Therefore, in the cluster chat server project based on muduo and nginx, I want to learn json and adopt json.

The following lists the serialization and deserialization codes of Json data used in some projects for reference only! The use of JSON for Modern C + + is very simple, as shown below:

#include "json.hpp"
using json = nlohmann::json;

Json data serialization

We program with vscode under linux.
I create a test folder under the chatserver folder and a testjson folder in the test folder, which is dedicated to the practice of json.

We create a file in the testjson folder: testjson cpp
We put JSON Download HPP, pull it to linux, and move it to the testjson folder.


json serialization example 1 (normal data serialization)
Next, we write testjson cpp

#include "json.hpp"
using json = nlohmann::json;

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

//json serialization example 1
void func1()
{
    json js;//Define an object of json type / / add an array
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
    
    cout<<js<<endl;
}

int main()
{
    func1();
    return 0;
}

Save, run

There are keys and values
But it's out of order! Underlying linked hash table

We do the cluster chat server project to convert json into a string and send it through the network.

#include "json.hpp"
using json = nlohmann::json;

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

//json serialization example 1
string func1()
{
    json js;
    js["msg_type"] = 2;
    js["from"] = "zhang san";
    js["to"] = "li si";
    js["msg"] = "hello, what are you doing now?";

    string sendBuf = js.dump();//Meaning of output 
    //cout<<sendBuf. c_ str()<<endl;// Convert to char*
    return sendBuf;
}

json serialization example 2 (array)
We write testjson cpp
The key of json can be integer type, string type, or array type.

//json serialization example 2
string func2()
{
    json js;
    //Add array
    js["id"] = {1, 2, 3, 4, 5};
    //Add key value
    js["name"] = "zhang san";
    //Add object
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    //The above is equivalent to the following sentence: add an array object at one time
    js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello china"}};
    //cout << js << endl;
    return js.dump();
}
#include "json.hpp"
using json = nlohmann::json;

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

//json serialization example 1
string func1()
{
    json js;//Define an object of json type / / add an array
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//Meaning of output 
    //cout<<sendBuf. c_ str()<<endl;// Convert to char*
    return sendBuf;
}

//json serialization example 2
void func2()
{
    json js;
    //Add array
    js["id"] = {1, 2, 3, 4, 5};
    //Add key value
    js["name"] = "zhang san";
    //Add object
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    //The above is equivalent to the following sentence: add an array object at one time
    js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello china"}};
    cout << js << endl;
    //return js.dump();
}

int main()
{
    //func1();
    func2();
    return 0;
}

function

json serialization example 3 (container serialization)
We write testjson cpp
Powerful enough to directly serialize the contents of the container in C++ STL into Json strings

#include "json.hpp"
using json = nlohmann::json;

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

//json serialization example 1
string func1()
{
    json js;//Define an object of json type / / add an array
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//Meaning of output 
    //cout<<sendBuf. c_ str()<<endl;// Convert to char*
    return sendBuf;
}

//json serialization example 2
string func2()
{
    json js;
    //Add array
    js["id"] = {1, 2, 3, 4, 5};
    //Add key value
    js["name"] = "zhang san";
    //Add object
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    //The above is equivalent to the following sentence: add an array object at one time
    js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello china"}};
    //cout << js << endl;
    return js.dump();
}

//json serialization example code 3
void func3()
{
    json js;

    //Serialize a vector container directly
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);

    js["list"] = vec;

    //Serialize a map container directly
    map<int, string> m;
    m.insert({1, "Mount Huangshan"});
    m.insert({2, "Huashan Mountain"});
    m.insert({3, "Mount Tai"});

    js["path"] = m;

    //string sendBuf = js.dump(); // json data object = serialize json string
    cout<<js<<endl;
    //return sendBuf;
}
int main()
{
    //func1();
    //unc2();
    func3();
    return 0;
}

function

We can convert json into a string and send it to the network

#include "json.hpp"
using json = nlohmann::json;

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

//json serialization example 1
string func1()
{
    json js;//Define an object of json type / / add an array
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//Meaning of output 
    //cout<<sendBuf. c_ str()<<endl;// Convert to char*
    return sendBuf;
}

//json serialization example 2
string func2()
{
    json js;
    //Add array
    js["id"] = {1, 2, 3, 4, 5};
    //Add key value
    js["name"] = "zhang san";
    //Add object
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    //The above is equivalent to the following sentence: add an array object at one time
    js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello china"}};
    //cout << js << endl;
    return js.dump();
}

//json serialization example code 3
string func3()
{
    json js;

    //Serialize a vector container directly
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);

    js["list"] = vec;

    //Serialize a map container directly
    map<int, string> m;
    m.insert({1, "Mount Huangshan"});
    m.insert({2, "Huashan Mountain"});
    m.insert({3, "Mount Tai"});

    js["path"] = m;

    string sendBuf = js.dump(); // json data object = serialize json string
    //cout<<sendBuf<<endl;
    return sendBuf;
}

int main()
{
    //func1();
    //unc2();
    func3();
    return 0;
}

Json data deserialization

When the string received from the network is in Json format, you can use JSON for Modern C + + to directly deserialize data or directly deserialize objects or even containers, which is extremely powerful!

int main()
{
    string recvBuf = func1();
    //Deserialization of data json string = > deserialization of data object (as a container for easy access)
    
    json jsbuf = json::parse(recvBuf);
    cout<<jsbuf["msg_type"]<<endl;
    cout<<jsbuf["from"]<<endl;
    cout<<jsbuf["to"]<<endl;
    cout<<jsbuf["msg"]<<endl;

    return 0;
}

function

The inverse sequences of other functions, such as implementations, are included below, which I summarized

testjson.cpp

#include "json.hpp"
using json = nlohmann::json;

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

//json serialization example 1
string func1()
{
    json js;//Define an object of json type / / add an array
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//Meaning of output 
    //cout<<sendBuf. c_ str()<<endl;// Convert to char*
    return sendBuf;
}

//json serialization example 2
string func2()
{
    json js;
    //Add array
    js["id"] = {1, 2, 3, 4, 5};
    //Add key value
    js["name"] = "zhang san";
    //Add object
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    //The above is equivalent to the following sentence: add an array object at one time
    js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello china"}};
    //cout << js << endl;
    return js.dump();
}

//json serialization example code 3
string func3()
{
    json js;

    //Serialize a vector container directly
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);

    js["list"] = vec;

    //Serialize a map container directly
    map<int, string> m;
    m.insert({1, "Mount Huangshan"});
    m.insert({2, "Huashan Mountain"});
    m.insert({3, "Mount Tai"});

    js["path"] = m;

    string sendBuf = js.dump(); //json data object = serialize json string
    //cout<<sendBuf<<endl;
    return sendBuf;
}

int main()
{
    //func1();
    //unc2();
    //func3();
    string recvBuf = func1();
    //string recvBuf = func2();
    //string recvBuf = func3();
    
    //Deserialization of data json string = > deserialization of data object (as a container for easy access)
    json jsbuf = json::parse(recvBuf);
    
    cout<<jsbuf["msg_type"]<<endl;
    cout<<jsbuf["from"]<<endl;
    cout<<jsbuf["to"]<<endl;
    cout<<jsbuf["msg"]<<endl;

    //cout<<jsbuf["id"]<<endl;
    //auto arr = jsbuf["id"];
    //cout<<arr[2]<<endl;

    //auto msgjs = jsbuf["msg"];
    //cout<<msgjs["zhang san"]<<endl;
    //cout<<msgjs["liu shuo"]<<endl;

    //vector<int> vec = jsbuf["list"]; // The array type in the JS object is directly put into the vector container
    //for (int &v : vec)
    //{
    //     cout << v << " ";
    //}
    //cout << endl;

    //map<int, string> mymap = jsbuf["path"];
    //for (auto &p : mymap)
    //{
    //     cout << p.first << " " << p.second << endl;
    //}
    //cout << endl;

    return 0;
}

Topics: Linux JSON