【Linux】【网络】协议:(序列化和反序列化)json 的安装和简单使用

文章目录

  • 1. 下载 json
  • 2. 基本使用
      • value 类型:万能类型
      • Writer 类型:序列化
      • Reader 类型:反序列化
  • 3. 使用举例

1. 下载 json

yum makecache fast
yum -y install jsoncpp-devel

2. 基本使用

  • 头文件:
#include 
  • 编译时需要加上 -ljsoncpp

value 类型:万能类型

  • json::value:是一种万能对象类型,能接收任意 kv 类型,储存的值会自动转成 字符串类型

  • 使用 中括号 [] 进行 定义拿取

  • asInt():可以将提取的 string,转化成 int 类型

Writer 类型:序列化

  • json::FastWriter:用于快速序列化的数据类型,即,可以将 struct 转成 string,用于传输

  • json::StyleWriter:也是用于序列化的数据类型,格式更加清楚美观

  • write():将 value 类,以序列化 string 格式,写入网络

Reader 类型:反序列化

  • json::Reader:用于反序列化的数据类型,即,可以将从网络接收到的 stirng 转成 struct,用于业务处理

  • json::StyleWriter:也是用于序列化,格式更加清楚美观

  • parse():从相应的流(网络)里面,将 string 信息读取到 json::Value 中去

  • 使用中括号可以对内容进行提取,asInt() 可以将 string 转化成 int 类型

3. 使用举例

此处举例协议内容为:整数的加减乘除取模的运算及输出方式。

// 【请求】
class Request
{
public:
    Request() {}
    Request(int x, int y, char op) : _x(x), _y(y), _op(op)
    {
    }
    // struct->string
    // "_x _op _y"
    bool Serialize(std::string *outStr)
    {
        *outStr = "";
        Json::Value root; 
        
        root["x"] = _x; 
        root["y"] = _y;
        root["op"] = _op;
        Json::StyledWriter writer;	// Json::FastWriter writer; 
        *outStr = writer.write(root);
        return true;
    }
    // string->struct
    bool Deserialize(const std::string &inStr)
    {
        Json::Value root;
        Json::Reader reader; 
        reader.parse(inStr, root);

        _x = root["x"].asInt();     // json::Value root 里面全是string,需要类型转换一下
        _y = root["y"].asInt();
        _op = root["op"].asInt();   // op也转成int,放入char里会被解释成操作符
        return true;
    }
    ~Request() {}

public:
    int _x;
    int _y;
    char _op;
};

// 【相应】
class Response
{
public:
    Response() {}
    Response(int result, int code) : _result(result), _code(code)
    {
    }
    // struct->string
    bool Serialize(std::string *outStr)
    {
        *outStr = "";
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;

        // Json::FastWriter writer;
        Json::StyledWriter writer;

        *outStr = writer.write(root);
        return true;
    }
    // string->struct
    bool Deserialize(const std::string &inStr)
    {
        Json::Value root;
        Json::Reader reader;
        reader.parse(inStr, root);
        _result = root["result"].asInt();
        _code = root["code"].asInt();
        return true;
    }
    ~Response() {}

public:
    int _result;	// 计算结果
    int _code; 		// 正确和错误码
};

如果本文对你有些帮助,请给个赞或收藏,你的支持是对作者大大莫大的鼓励!!(✿◡‿◡) 欢迎评论留言~~


你可能感兴趣的:(Linux,网络,linux,json,运维)