01.json序列化

JSON for Modern C++ 是一个由德国大牛 nlohmann 编写的在 C++ 下使用的 JSON 库。
下载地址传送门:json下载
实例代码

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

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


//json 序列化1
void func1()
{
     json js;
     js["msg_type"]=2;
     js["from"]="ds";
     js["to"]="cs";
     js["msg"]="hello,go go go";

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


//json序列化2
void func2()
{
    json js;
    //添加数组
    js["id"]={1,2,3,4,5};
    //添加对象
    js["name"]="ds";
    //添加对象
    js["msg"]["ds"]="hello world";
    js["msg"]["cn"]="hello china";

    //等同于下面这句
    js["msg"]={{"ds","hello world"},{"cn","hello china"}};

    cout<<js<<endl;
    
}

//json实例化代码3
void func3()
{
    json js;

    //序列化一个vector容器
    vector<int>vec;
    vec.push_back(1);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);

    js["list"]=vec;

    //序列化一个map容器
    map<int,string>m;
    m.insert({1,"ds"});
    m.insert({2,"cn"});
    m.insert({3,"co"});
    m.insert({4,"os"});

    js["path"]=m;

    string sendBuf=js.dump();//json数据对象 ->序列化  json字符串
    cout<<sendBuf.c_str()<<endl;
}

int main()
{
    func1();
    func2();
    func3();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值