JsonCpp serialize vector which contains class

//Book.cpp
#include <iostream>

using namespace std;

class Book
{
public:
    int Idx; 
    char *ISBN;
    char *Name;
    char *Abstract;
    char *Content;
    char *Topic;
    char *Comment;
};


//main.cpp
#include <algorithm>
#include <iostream>
#include <fstream>
#include <functional>
#include <jsoncpp/json/json.h>
#include <string.h>
#include <string>
#include <uuid/uuid.h>
#include <vector>
#include "Model/Book.cpp"

using namespace std;

char *uuidValue = (char *)malloc(40);

char *getUuid()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID, uuidValue);
    return uuidValue;
}

void fillVector(vector<Book> &vec, int len)
{
    for(int i=0;i<len;i++)
    {
        Book bk;
        bk.Idx=i; 
        bk.ISBN=(char*)malloc(40);
        bk.Name=(char*)malloc(40);
        bk.Abstract=(char*)malloc(40);
        bk.Content=(char*)malloc(40);
        bk.Topic=(char*)malloc(40);
        bk.Comment=(char*)malloc(40);

        strcpy(bk.ISBN,getUuid());
        strcpy(bk.Name,getUuid());
        strcpy(bk.Abstract,getUuid());
        strcpy(bk.Content,getUuid());
        strcpy(bk.Topic,getUuid());
        strcpy(bk.Comment,getUuid());
        vec.push_back(bk);        
    }
}

void serializeVector(int len)
{
    vector<Book> vec;
    fillVector(std::ref(vec),len);
    Json::Value root; 
    for(auto &bk:vec)
    {
        Json::Value jsonBk;
        jsonBk["Idx"]=bk.Idx; 
        jsonBk["ISBN"]=bk.ISBN;
        jsonBk["Name"]=bk.Name;
        jsonBk["Abstract"]=bk.Abstract;
        jsonBk["Content"]=bk.Content;
        jsonBk["Topic"]=bk.Topic;
        jsonBk["Comment"]=bk.Comment;
        root.append(jsonBk);
    } 
    Json::StyledWriter sWriter;
    cout<<sWriter.write(root)<<endl; 
}

int main(int args,char **argv)
{
    serializeVector(atoi(argv[1]));
}

 

Compile

g++ -g -std=c++2a -I. *.cpp ./Model/*.cpp -o h1 -luuid -ljsoncpp

 

Run

./h1 5

 

posted @ 2022-11-28 15:02  FredGrit  阅读(23)  评论(0编辑  收藏  举报