【网络编程】第六章 json(安装+使用)

发布于:2024-08-26 ⋅ 阅读:(122) ⋅ 点赞:(0)


一、json

json安装

下载

sudo yum install jsoncpp-devel

json是一个kv键值对的序列化方式

{
	"data": "value"
}

头文件#include <jsoncpp/json/json.h>

序列化

void serialize(std::string& out)
{
    Json::Value root;//Value是万能变量
    root["x"] = _x;//序列化的时候会将所有内容转化为字符串
    root["y"] = _y;
    root["op"] = _ops;

    Json::FastWriter writer; // 这个是写成一行
    out = writer.write(root);//返回值string
}

反序列化

bool deserialize( std::string &in)
{
    Json::Value root;
    Json::Reader rd;
    rd.parse(in, root);
    _x = root["x"].asInt();//变成整形
    _y = root["y"].asInt();
    _ops = root["op"].asInt();
}

运行,编译的时候需要指定库名-ljsoncpp

g++ -o test test.cc -std=c++11 -ljsoncpp

命令行定义

源文件要用define 这样写#define MY_SELF 1

使用命令行参数方式代替修改源文件中的define,加上-DMY_SELF

g++ -DMY_SELF  tcpServer.cpp -o tcpServer -lpthread -ljsoncpp

对应makefile如下修改

.PHONY:all
all:tcpClient tcpServer
Mythod=-DMY_SELF 

tcpClient: tcpClient.cpp
	g++ $(Mythod) -o $@ $^ -std=c++11 -lpthread -ljsoncpp
tcpServer:tcpServer.cpp
	g++ $(Mythod) -o $@ $^ -std=c++11 -lpthread -ljsoncpp

.PHONY:clean
clean:
	rm -f tcpClient tcpServer

使用自己协议

Mythod=-DMY_SELF 

使用json,就把后面注释

Mythod=#-DMY_SELF


网站公告

今日签到

点亮在社区的每一天
去签到