栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

json的简单使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

json的简单使用

json的简单使用
  • 普通数据序列化
  • 数组序列化
  • 容器序列化
  • 数据反序列化

普通数据序列化
#include "json.hpp"
using json = nlohmann::json;

#include 
#include 
#include 
#include 
using namespace std;

//json序列化示例1
void func1()
{
    json js;//定义一个json类型的对象//添加数组
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
    
    cout< 

保存,运行。

数组序列化

json的键可以是整数类型,字符串类型,还可以是数组类型。

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

#include 
#include 
#include 
#include 
using namespace std;

//json序列化示例1
string func1()
{
    json js;//定义一个json类型的对象//添加数组
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//输出的意思 
    //cout< 

运行。

容器序列化

JSON for Modern C++ 可以把C++ STL中的容器内容可以直接序列化成Json字符串。

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

#include 
#include 
#include 
#include 
using namespace std;

//json序列化示例1
string func1()
{
    json js;//定义一个json类型的对象//添加数组
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//输出的意思 
    //cout< vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);

    js["list"] = vec;

    //直接序列化一个map容器
    map m;
    m.insert({1, "黄山"});
    m.insert({2, "华山"});
    m.insert({3, "泰山"});

    js["path"] = m;

    //string sendBuf = js.dump(); // json数据对象 =》序列化 json字符串
    cout< 

运行。

数据反序列化

当从网络接收到字符串为Json格式,可以用JSON for Modern C++ 直接反序列化取得数据或者直接反序列化出对象或者容器。

上述三个函数的反序列化如下所示:

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

#include 
#include 
#include 
#include 
using namespace std;

//json序列化示例1
string func1()
{
    json js;//定义一个json类型的对象//添加数组
    js["msg_type"] = 2;
    js["from"] = "linzeyu";
    js["to"] = "zhang san";
    js["msg"] = "hello, are you ok now?";
 
    string sendBuf = js.dump();//输出的意思 
    //cout< vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);

    js["list"] = vec;

    //直接序列化一个map容器
    map m;
    m.insert({1, "黄山"});
    m.insert({2, "华山"});
    m.insert({3, "泰山"});

    js["path"] = m;

    string sendBuf = js.dump(); //json数据对象 =》序列化 json字符串
    //cout< vec = jsbuf["list"]; //js对象里面的数组类型,直接放入vector容器当中
    //for (int &v : vec)
    //{
    //     cout << v << " ";
    //}
    //cout << endl;

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

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429943.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号