//Book.h #include <iostream> #include <jsoncpp/json/json.h> using namespace std; class Book { public: int Idx; unsigned long long Id; char *Name; char *Abstract; char *Content; char *Comment; char *Author; char *ISBN; char *Topic; void BookSerialize(Json::Value &obj) { obj["Idx"]=Idx; obj["Id"]=Id; obj["Name"]=Name; obj["Abstract"]=Abstract; obj["Content"]=Content; obj["Author"]=Author; obj["ISBN"]=ISBN; obj["Topic"]=Topic; } }; //main.cpp #include <ctime> #include <iostream> #include <jsoncpp/json/json.h> #include <fstream> #include <functional> #include <string.h> #include <uuid/uuid.h> #include <vector> #include "Model/Book.h" using namespace std; char *uuidValue = (char *)malloc(40); char *getUuid() { uuid_t newUUID; uuid_generate(newUUID); uuid_unparse(newUUID,uuidValue); return uuidValue; } char* dtValue=(char*)malloc(20); char* getTimeNow() { time_t rawTime=time(nullptr); struct tm tmInfo=*localtime(&rawTime); strftime(dtValue,20,"%Y%m%d%H%M%S",&tmInfo); return dtValue; } void getBookVector(vector<Book> &vec,int len) { for(int i=0;i<len;i++) { Book bk; bk.Idx=i; bk.Idx=(unsigned long long)i*i; bk.Abstract=(char*)malloc(40); bk.Author=(char*)malloc(40); bk.Comment=(char*)malloc(40); bk.Content=(char*)malloc(40); bk.ISBN=(char*)malloc(40); bk.Name=(char*)malloc(40); bk.Topic=(char*)malloc(40); strcpy(bk.Abstract,getUuid()); strcpy(bk.Author,getUuid()); strcpy(bk.Comment,getUuid()); strcpy(bk.Content,getUuid()); strcpy(bk.ISBN,getUuid()); strcpy(bk.Name,getUuid()); strcpy(bk.Topic,getUuid()); vec.push_back(bk); } } void logMsg(string fileName,string msg) { fstream wFile(fileName,ios::app); if(!wFile.is_open()) { cout<<"Open "<<fileName<<" failed!"<<endl; return; } wFile<<msg<<endl; wFile.close(); cout<<getTimeNow()<<" write into "<<fileName<<" succeed!"<<endl; } void SerializeVector(int len) { vector<Book> vec; getBookVector(std::ref(vec),len); Json::Value rootObj; for(int i=0;i<len;i++) { Json::Value obj; vec[i].BookSerialize(std::ref(obj)); rootObj.append(obj); } Json::StyledWriter sWriter; string jsonValue=sWriter.write(rootObj); string fileName(getTimeNow()); fileName.append(".txt"); logMsg(fileName,jsonValue); } int main(int args,char ** argv) { SerializeVector(atoi(argv[1])); }
Compile in g++
g++ -g -std=c++2a -I. *.cpp ./Model/*.h -o h1 -ljsoncpp -luuid
Run
./h1 100
标签:std,obj,int,serialize,char,vector,ISBN,include,class From: https://www.cnblogs.com/Fred1987/p/16944010.html