前端之家收集整理的这篇文章主要介绍了
jsoncpp序列化与反序列化,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//my_json.h
#include"comm.h"
#include<iostream>
#include<string>
#include"json/json.h"
usingnamespacestd;
classmy_json
{
public:
my_json();
~my_json();
staticintserialize(Json::Value&in_val,string&out_str);
staticintdeserialize(string&in_out,Json::Value&out_val);
private:
};
//my_json.cpp
#include"my_json.h"
my_json::my_json()
{}
intmy_json::serialize(Json::Value&in_val,string&out_str)
{
#ifdef_FAST_JSON_
Json::FastWriterwrite;
out_str=write.write(in_val);
#else
Json::StyledWriterwrite;
out_str=write.write(in_val);
#endif
return0;
}
intmy_json::deserialize(string&in_str,Json::Value&out_val)
{
Json::Readerread;
if(read.parse(in_str,out_val,false))
{
//cout<<in_str<<endl;
return0;
}
return-1;
}
my_json::~my_json()
{}
//udp_data.h
#pragmaonce
#include"comm.h"
#include"my_json.h"
#include<iostream>
usingnamespacestd;
classudp_data
{
public:
udp_data();
voiddata_to_string(string&_in_name,string&_in_msg,string&_in_school,string_in_cmd,string&_out_str);
voiddata_to_value(string&_out_name,string&_out_msg,string&_out_school,string&_out_cmd,string&_in_str);
~udp_data();
public:
stringnick_name;
stringmsg;
stringschool;
stringcmd;
};
//udp_data.cpp
#include"udp_data.h"
udp_data::udp_data()
{}
voidudp_data::data_to_string(string&_in_name,string&_out_str)
{
nick_name=_in_name;
msg=_in_msg;
school=_in_school;
cmd=_in_cmd;
Json::Valueroot;
root["nick_name"]=nick_name;
root["msg"]=msg;
root["school"]=school;
root["cmd"]=cmd;
my_json::serialize(root,_out_str);
//cout<<_in_name<<endl;
//cout<<_out_str<<endl;
}
voidudp_data::data_to_value(string&_out_name,string&_in_str)
{
Json::Valueroot;
my_json::deserialize(_in_str,root);
_out_name=root["nick_name"].asString();
//cout<<_out_name<<endl;
_out_msg=root["msg"].asString();
//cout<<_out_msg<<endl;
_out_school=root["school"].asString();
_out_cmd=root["cmd"].asString();
nick_name=_out_name;
msg=_out_msg;
school=_out_school;
cmd=_out_cmd;
//cout<<cmd;
}
udp_data::~udp_data()
{}
//intmain()
//{
//udp_dataud;
//string_name;
////cout<<"pleaseinputname:";
////cin>>_name;
//string_msg;
////cout<<"pleaseinputmsg:";
////cin>>_msg;
//string_school;
////cout<<"pleaseinputschool:";
////cin>>_school;
//string_cmd;
////cout<<"pleaseinputcmd:";
////cin>>_cmd;
//string_out="{\"cmd\":\"None\",\"msg\":\"hello\",\"nick_name\":\"rz\",\"school\":\"xpu\"}";
////_name="rz";
////ud.data_to_string(_name,_msg,_school,_cmd,_out);
////_name="";
//ud.data_to_value(_name,_out);
////cout<<_out<<endl;
//cout<<_name<<endl;
//cout<<_msg<<endl;
//cout<<_school<<endl;
//cout<<_cmd<<endl;
//return0;
//}
//Makefile
ROOT_PATH=$(shellpwd)
INCLUDE=-I../lib/include
LIB=#-L$(ROOT_PATH)/lib/lib
.PHONY:all
all:udp_data
udp_data:udp_data.omy_json.o
g++-o$@$^/home/xiaozhi/LinuxStudy/project_2/lib/lib/libjsoncpp.a
udp_data.o:udp_data.cpp
g++-c$<$(INCLUDE)
my_json.o:my_json.cpp
g++-c$<$(INCLUDE)-D_FAST_JSON_
.PHONY:clean
clean:
rm-fudp_datamy_json*.o
原文链接:https://www.f2er.com/json/289296.html