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 @   FredGrit  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2021-11-28 c convert char pointer and char array interactively via strcpy
2021-11-28 C FILE fopen fputs strcat, write content to file via FILE;
2019-11-28 C# detect latest .net framework installed on PC
2016-11-28 Dictionary<string, Dictionary<string, Person>> dic = new Dictionary<string, Dictionary<string, Person>>();
点击右上角即可分享
微信分享提示