Json序列化和反序列化 笔记

跟着施磊老师学C++

下载:GitHub – nlohmann/json: JSON for Modern C++

在single_include/nlohmann里头有一个json.hpp,把它放到我们的项目中就可以了

Json序列化和反序列化 笔记

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

#include 
#include 
#include 
#include 

using namespace std;
/*
    Json数据序列化
    :就是把我们想要打包的数据,或者对象,直接处理成Json字符串
*/ 
// json序列化示例1
string func1() {     普通数据序列化
    json js;
    js["msg_type"] = 2;
    js["from"] = "呵呵哒";
    js["to"] = "小比尔";
    js["msg"] = "hello,what are you doing now?";
    std::cout << js << std::endl;
    // {"from":"呵呵哒","msg":"hello,what are you doing now?","msg_type":2,"to":"小比尔"}

    string sendBuf = js.dump();
    // cout << sendBuf.c_str() << endl;
    return sendBuf;
}

// json 序列化示例2  普通数据序列化
string func2() {
    json js;
    // 添加数组
    js["id"] = {1,2,3,4,5};
    // 添加key-value
    js["name"] = "张三";
    // 添加对象
    js["msg"]["张三"] = "hello world";
    js["msg"]["李四"] = "hello china";
    // 上面等同于下面这句一次性添加数组对象
    js["msg"] = {{"张三","hello world"},{"李四","hello china"}};
    std::cout << js << std::endl;
    // {"id":[1,2,3,4,5],"msg":{"张三":"hello world","李四":"hello china"},"name":"张三"}
    string sendBuf = js.dump();
    // cout << sendBuf.c_str() << endl;
    return sendBuf;
}

// json序列化示例代码3    容器序列化
string func3() {
    json js;
    // 直接序列化一个vector容器
    vector vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);
    js["list"] = vec;

    // 直接序列化一个map容器
    map m;
    m.insert(make_pair(1,"刘备"));
    m.insert(make_pair(2,"关羽"));
    m.insert(make_pair(3,"张飞"));

    js["hero"] = m;
    std::cout << js < 序列化 json字符串
    // cout << sendBuf.c_str() < 反序列化 数据对象(看作容器,方便访问)
    json jsbuf = json::parse(recvBuf);
    cout<<jsbuf["msg_type"]<<endl;
    cout<<jsbuf["from"]<<endl;
    cout<<jsbuf["to"]<<endl;
    cout<<jsbuf["msg"]< 反序列化 数据对象(看作容器,方便访问)    
    json jsbuf = json::parse(recvBuf);
    cout<<jsbuf["id"]<<endl;
    cout<<jsbuf["name"]<<endl;
    cout<<jsbuf["msg"]<<endl;

    auto arr = jsbuf["id"];
    for(auto it = arr.begin(); it != arr.end(); it++) {
        cout<<*it<<" ";
    }
    cout<<endl;

    // auto msgmap = jsbuf["msg"];
    // for(auto it = msgmap.begin(); it != msgmap.end(); it++) {
    //     cout<<it.key()< "<<it.value()<<endl;
    // }
    map msgmap = jsbuf["msg"];
    for(auto &mp : msgmap) {
        cout<<mp.first< "<<mp.second<<endl;
    }
    cout< 反序列化 数据对象(看作容器,方便访问)    
    json jsbuf = json::parse(recvBuf);
    cout<<jsbuf["list"]<<endl;
    cout<<jsbuf["hero"]<<endl;

    vector vec = jsbuf["list"];// js 对象里面的数组类型,直接放入vector容器当中
    for(auto it = vec.begin(); it != vec.end(); it++) {
        cout<<*it<<" ";
    }
    cout<<endl;

    map mymap = jsbuf["hero"];
    for(auto &mp:mymap) {
        cout<<mp.first< "<<mp.second<<endl;
    }
    cout<<endl;
}

int main() {
    test2();
    test3();
    return 0;
}

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/3f3f532b5d.html