首页 > 其他分享 >cpp jsoncpp serialize vector class into plain text file and deserialize from plain text file into ve

cpp jsoncpp serialize vector class into plain text file and deserialize from plain text file into ve

时间:2022-12-27 23:11:39浏览次数:55  
标签:string plain into vector vec include itr book

//model/book.h
#pragma once
#ifndef __book_h__
#define __book_h__
#include <iostream>

using namespace std;

struct book
{
    uint64_t idx;
    uint64_t id;
    string name;
    string abstract;
    string author;
    string comment;
    string content;
    string summary;
    string topic;
};

#endif

//model/util.h
#pragma once
#ifndef __util_h__
#define __util_h__
#include <chrono>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>
#include <jsoncpp/json/json.h>
#include "model/book.h"

using namespace std;

class util
{
public:
    string get_time_now();
    string get_uuid();
    void fill_book_vector(vector<book> &vec, int len);
    void print_book_vector(vector<book> &vec);
    void book_vector_demo(int len);
    void serialize_book_vector(vector<book>&vec);
    void log_file_msg(string fileName,string msg);
    void serialize_book_demo(int len);
    void deserialize_string_to_vector(string filename);
};

#endif

//model/util.cpp
#include "model/util.h"

std::string util::get_time_now()
{
    chrono::time_point<chrono::high_resolution_clock> now = chrono::high_resolution_clock::now();
    auto ms = chrono::duration_cast<chrono::milliseconds>(now.time_since_epoch()) % 1000;
    time_t rawTime = chrono::high_resolution_clock::to_time_t(now);
    struct tm tmInfo = *localtime(&rawTime);
    stringstream ss;
    ss << std::put_time(&tmInfo, "%Y%m%d%H%M%S") << std::setfill('0') << std::setw(3) << ms.count();
    string dtStr = ss.str();
    ss = stringstream();
    ss.str(std::string());
    return dtStr;
}

std::string util::get_uuid()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    char *uuidValue = (char *)malloc(40);
    uuid_unparse(newUUID, uuidValue);
    string uuidStr(uuidValue);
    free(uuidValue);
    uuidValue = nullptr;
    return uuidStr;
}

void util::fill_book_vector(vector<book> &vec, int len)
{
    for (int i = 0; i < len; i++)
    {
        book bk;
        bk.idx = static_cast<uint64_t>(i);
        bk.id = static_cast<uint64_t>(i * i * i * i * i);
        bk.abstract.assign(get_uuid());
        bk.author.assign(get_uuid());
        bk.comment.assign(get_uuid());
        bk.content.assign(get_uuid());
        bk.name.assign(get_uuid());
        bk.summary.assign(get_uuid());
        bk.topic.assign(get_uuid());
        vec.push_back(bk);
    }
}

void util::print_book_vector(vector<book> &vec)
{
    vector<book>::iterator itr = vec.begin();
    while (itr != vec.end())
    {
        cout << fixed << itr->idx << "," << itr->id << "," << itr->abstract << "," << itr->author << "," << itr->comment << "," << itr->content << ","
             << itr->name << "," << itr->summary << "," << itr->topic << endl;
        itr++;
    }
}

void util::book_vector_demo(int len)
{
    vector<book> vec;
    fill_book_vector(std::ref(vec), len);
    print_book_vector(std::ref(vec));
    cout << get_time_now() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

void util::serialize_book_vector(vector<book> &vec)
{
    Json::Value root;
    vector<book>::iterator itr = vec.begin();
    while (itr != vec.end())
    {
        Json::Value value;
        value["idx"] = itr->idx;
        value["id"] = itr->id;
        value["author"] = itr->author;
        value["abstract"] = itr->abstract;
        value["comment"] = itr->comment;
        value["content"] = itr->content;
        value["name"] = itr->name;
        value["summary"] = itr->summary;
        value["topic"] = itr->topic;
        root.append(value);
        itr++;
    }

    Json::StyledWriter styledWriter;
    string jsonValue = styledWriter.write(root);
    string fileName = get_time_now().append(".txt");
    log_file_msg(fileName, jsonValue);
    cout << get_time_now() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

void util::log_file_msg(string fileName, string msg)
{
    fstream wFile(fileName, ios::app);
    if (!wFile.good())
    {
        cout << "Create or open " << fileName << " failed!" << endl;
        return;
    }
    wFile << msg;
    wFile.close();
    cout << get_time_now() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

void util::serialize_book_demo(int len)
{
    vector<book> vec;
    fill_book_vector(std::ref(vec), len);
    cout << "size=" << vec.size() << endl;
    serialize_book_vector(std::ref(vec));
    cout << get_time_now() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

void util::deserialize_string_to_vector(string filename)
{
    fstream rFile(filename, ios::in);
    if (!rFile.good())
    {
        cout << "Open " << filename << " failed!" << endl;
        return;
    }

    vector<book> vec;
    stringstream ss;
    ss << rFile.rdbuf();
    string jsonvalue = ss.str();
    Json::Value jsonroot;
    Json::Reader jsonreader;
    if (!jsonreader.parse(jsonvalue, jsonroot))
    {
        cout << "Json parsed failed!" << endl;
        return;
    }

    Json::Value::const_iterator citr = jsonroot.begin();
    while (citr != jsonroot.end())
    {
        book bk;
        bk.idx = (*citr)["idx"].asUInt64();
        bk.id = (*citr)["id"].asUInt64();
        bk.abstract = (*citr)["abstract"].asString();
        bk.author = (*citr)["author"].asString();
        bk.comment = (*citr)["comment"].asString();
        bk.content = (*citr)["content"].asString();
        bk.name = (*citr)["name"].asString();
        bk.summary = (*citr)["summary"].asString();
        bk.topic = (*citr)["topic"].asString();
        vec.push_back(bk);
        citr++;
    }

    print_book_vector(std::ref(vec));
    cout << get_time_now() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

//main.cpp
#include "model/util.h"

void serialize_book_vector_demo(int len)
{
    util ul;
    ul.serialize_book_demo(len);
}

void deserialize_book_vector_demo(string filename)
{
    util ul;
    ul.deserialize_string_to_vector(filename);
}

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

 

Compile via g++

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

 

 

 

//main.cpp
#include "model/util.h"
 
void serialize_book_vector_demo(int len)
{
    util ul;
    ul.serialize_book_demo(len);
}

void deserialize_book_vector_demo(string filename)
{
    util ul;
    ul.deserialize_string_to_vector(filename);
}

int main(int args,char **argv)
{
    serialize_book_vector_demo(atoi(argv[1]));
    // deserialize_book_vector_demo(argv[1]);
}
g++ -g -std=c++2a -I. *.cpp ./model/*.cpp -o h1 -luuid -ljsoncpp

 

 

 

标签:string,plain,into,vector,vec,include,itr,book
From: https://www.cnblogs.com/Fred1987/p/17009221.html

相关文章

  • What Is Bubble Tea? Bubble Tea Explained
    ​WhatIsBubbleTea?Bubbleteaisaconcoctionbetweenblacktea,milk,ice,andchewytapiocapearls.Ifbysomestrokeofbadluckyouhaveneverhadorhear......
  • STL库之动态数组vector基本使用方法
    前言:有些时候想开一个数组,但是不知道开多大长度的数组合适,因为我们要用到的数组可能会根据情况变得变动。这时候我们就要用到动态数组。所谓动态数组,也就是不定长数组,数组的......
  • sql优化之explain
    1.explain的介绍explain可以显示mysql是如何执行sql语句的,以便我们知道sql语句的性能瓶颈在哪,帮助我们进行相关的性能优化。2.explain的使用方法explain的使用方法比......
  • vector 内存释放相关
    在使用vector存储char类型时new的数据在vecto执行rerase的时候或者单项执行clear内存是不能被释放的。比如有下面的一个测试:classSnapshotInfo{public:......
  • 【机器学习】李宏毅——Explainable ML(可解释性的机器学习)
    在前面的学习之中,我们已经学习了很多的模型,它能够针对特定的任务,接受我们的输入并产生目标的输出。但我们并不满足于此,我们甚至希望机器告诉我们,它是如何得到这个答案的,而......
  • Machine Learning Explainability
    MachineLearningExplainabilityExtracthuman-understandableinsightsfromanymodel.PermutationImportanceWhatfeaturesdoesyourmodelthinkareimportant?......
  • Hinton坐阵!斯坦福CS25 Transformer专题讲座更新:多位AI大佬齐聚
    编辑:DavidJoey【导读】斯坦福大牛ChristopherManning开设的Transformer联合讲座课程更新啦!这期请来的是Hinton大神。图灵奖得主、深度学习教父GeoffreyHinton在斯坦福线......
  • List接口-ArrayList、LinkedList和Vector
    1.List接口和常用方法1.1List接口基本介绍importjava.util.ArrayList;importjava.util.List;publicclassList_{@SuppressWarnings({"all"})public......
  • insert into,insert into select,re
       1、replaceinto REPLACE的运行与INSERT很相似。只有一点例外:假如表中的一个旧记录与一个用于PRIMARYKEY或一个UNIQUE索引的新记录具有相同的值,则在新记录被插入之前......
  • ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For det
    出现这个错误表示rabbiMQ拒绝使用普通身份验证机制拒绝登录,解决的方法很简单解决办法在rabbitMq的后台创建一个不普通的用户就好了,具体步骤如下:进入admin界面,添加一个......