cpp jsoncpp serialize anddeserialize complete example

//Model/Book.h
#pragma once
#ifndef __Book_H__
#define __Book_H__
#include <chrono>
#include <ctime>
#include <fstream>
#include <iostream>
#include <jsoncpp/json/json.h>
#include <iomanip>
#include <string.h>
#include <string>
#include <uuid/uuid.h>

using namespace std;
using namespace std::chrono;

class Book
{
public:
    static char *uuidValue;
    char *getUuidValue();
    string getTimeNow();
    string getTimeNow2();
    uint64_t idx;
    uint64_t id;
    char *abstract;
    char *author;
    char *comment;
    char *content;
    char *name;
    char *summary;
    char *title;
    char *topic;

    void serializeBookVector(vector<Book> &vec, Json::Value &root);
    void fillBookVector(vector<Book> &vec, int len);
    void logFile(string fileName, string msg);
    void serializeBookVectorDemo(int len);
    bool operator>(const Book &other);
    bool operator==(const Book &other);
    bool operator=(const Book &other);
    void deserializeBook(const string &fileName);
    string readFile(string fileName);
    void printBookVector(vector<Book> &vec);
};

#endif

//Model/Book.cpp
#include "Model/Book.h"

char *Book::uuidValue = (char *)malloc(40);
string Book::getTimeNow()
{
    time_point now = chrono::system_clock::now();
    chrono::milliseconds ms = duration_cast<chrono::milliseconds>(now.time_since_epoch()) % 1000;
    time_t timer = system_clock::to_time_t(now);
    std::tm tmInfo = *localtime(&timer);
    stringstream oss;
    oss << std::put_time(&tmInfo, "%Y%m%d%H%M%S") << std::setfill('0') << std::setw(3) << ms.count();
    return oss.str();
}

char *Book::getUuidValue()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID, uuidValue);
    return uuidValue;
}

void Book::serializeBookVector(vector<Book> &vec, Json::Value &root)
{
    int len = vec.size();
    for (int i = 0; i < len; i++)
    {
        Json::Value jsonBook;
        jsonBook["id"]=Json::Value::UInt64(vec[i].id);
        jsonBook["idx"] = Json::Value::UInt64(vec[i].idx);
        jsonBook["abstract"] = vec[i].abstract;
        jsonBook["author"] = vec[i].author;
        jsonBook["comment"] = vec[i].comment;
        jsonBook["content"] = vec[i].content;
        jsonBook["name"] = vec[i].name;
        jsonBook["summary"] = vec[i].summary;
        jsonBook["title"] = vec[i].title;
        jsonBook["topic"] = vec[i].topic;
        root.append(jsonBook);
        free(vec[i].abstract);
        free(vec[i].author);
        free(vec[i].comment);
        free(vec[i].content);
        free(vec[i].name);
        free(vec[i].summary);
        free(vec[i].title);
        free(vec[i].topic);
    }
}

void Book::fillBookVector(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);
        bk.abstract = (char *)malloc(40);
        bk.author = (char *)malloc(40);
        bk.comment = (char *)malloc(40);
        bk.content = (char *)malloc(40);
        bk.name = (char *)malloc(40);
        bk.summary = (char *)malloc(40);
        bk.title = (char *)malloc(40);
        bk.topic = (char *)malloc(40);
        strcpy(bk.abstract, getUuidValue());
        strcpy(bk.author, getUuidValue());
        strcpy(bk.comment, getUuidValue());
        strcpy(bk.content, getUuidValue());
        strcpy(bk.name, getUuidValue());
        strcpy(bk.summary, getUuidValue());
        strcpy(bk.title, getUuidValue());
        strcpy(bk.topic, getUuidValue());
        vec.push_back(bk);
    }
}

void Book::logFile(string fileName, string msg)
{
    fstream wFile(fileName, ios::app);
    if (!wFile.is_open())
    {
        cout << "Create or open " << fileName << " failed!" << endl;
        return;
    }

    wFile << msg << endl
          << endl;
    wFile.close();
    cout << getTimeNow() << ", finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

void Book::serializeBookVectorDemo(int len)
{
    vector<Book> vec;
    fillBookVector(std::ref(vec), len);
    Json::Value root;
    serializeBookVector(std::ref(vec), std::ref(root));
    Json::StyledWriter writer;
    string jsonValue = writer.write(std::ref(root));
    string fileName(getTimeNow());
    fileName = fileName.append(".txt");
    logFile(fileName, jsonValue);
    cout << getTimeNow() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
}

string Book::getTimeNow2()
{
    time_point now = chrono::system_clock::now();
    chrono::milliseconds ms = duration_cast<chrono::milliseconds>(now.time_since_epoch()) % 1000;
    time_t rawTime = system_clock::to_time_t(now);
    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 str = ss.str();
    ss = stringstream();
    return str;
}

bool Book::operator>(const Book &other)
{
    return idx > other.idx;
}

bool Book::operator==(const Book &other)
{
    return idx == other.idx && author == other.author && abstract == other.abstract && name == other.name && comment == other.comment && content == other.content && summary == other.summary && title == other.title && topic == other.topic;
}

bool Book::operator=(const Book &other)
{
    idx = other.idx;
    abstract = (char *)malloc(40);
    author = (char *)malloc(40);
    comment = (char *)malloc(40);
    content = (char *)malloc(40);
    name = (char *)malloc(40);
    summary = (char *)malloc(40);
    title = (char *)malloc(40);
    topic = (char *)malloc(40);
    strcpy(abstract, other.abstract);
    strcpy(author, other.author);
    strcpy(comment, other.comment);
    strcpy(content, other.content);
    strcpy(name, other.name);
    strcpy(summary, other.summary);
    strcpy(title, other.title);
    strcpy(topic, other.topic);
    return this;
}

string Book::readFile(string fileName)
{
    fstream rFile(fileName, ios::in);
    if (!rFile.is_open())
    {
        cout << "Open " << fileName << " failed!" << endl;
        return nullptr;
    }
    stringstream ss;
    ss << rFile.rdbuf();
    string str = ss.str();
    ss = stringstream();
    ss.str(std::string());
    return str;
}

void Book::printBookVector(vector<Book> &vec)
{
    vector<Book>::iterator itr = vec.begin();
    while (itr != vec.end())
    {
        cout<<"idx=" <<itr->idx<<",id="<<itr->id << ",abstract=" << itr->abstract << ",author=" << itr->author << ",comment=" 
        << itr->comment << ",content=" << itr->content << ",name=" << itr->name << ",summary=" << itr->summary 
        << ",title=" << itr->title << ",topic=" << itr->topic << endl<<endl;
        free(itr->abstract);
        free(itr->author);
        free(itr->comment);
        free(itr->content);
        free(itr->name);
        free(itr->summary);
        free(itr->title);
        free(itr->topic);
        itr++;
    }
    cout << getTimeNow2() << ",finished in " << __FUNCTION__ << endl;
}

void Book::deserializeBook(const string &fileName)
{
    // fstream readFile(fileName, ios::in);
    string jsonValue = readFile(fileName);
    vector<Book> vec;
    Json::Reader jReader;
    Json::Value jsonRoot;
    if (jReader.parse(jsonValue, jsonRoot))
    { 
        for (Json::Value::iterator itr = jsonRoot.begin(); itr != jsonRoot.end(); itr++)
        {
            Json::Value jsonBk = *itr;
            Book bk;
            bk.abstract = (char *)malloc(40);
            bk.author = (char *)malloc(40);
            bk.comment = (char *)malloc(40);
            bk.content = (char *)malloc(40);
            bk.name = (char *)malloc(40);
            bk.summary = (char *)malloc(40);
            bk.title = (char *)malloc(40);
            bk.topic = (char *)malloc(40);
            bk.idx = jsonBk["idx"].asUInt64();
            bk.id=jsonBk["id"].asUInt64();
            strcpy(bk.abstract, (char *)(jsonBk["abstract"].asCString()));
            strcpy(bk.author, (char *)(jsonBk["author"].asCString()));
            strcpy(bk.comment, (char *)(jsonBk["comment"].asCString()));
            strcpy(bk.content, (char *)(jsonBk["content"].asCString()));
            strcpy(bk.summary, (char *)(jsonBk["summary"].asCString()));
            strcpy(bk.title, (char *)(jsonBk["title"].asCString()));
            strcpy(bk.topic, (char *)(jsonBk["topic"].asCString()));
            vec.push_back(bk);
        }
    } 
    printBookVector(std::ref(vec));
    cout << getTimeNow2() << ", finished in " << __FUNCTION__ << endl;
}

//main.cpp
#include "Model/Book.h"

int main(int args, char **argv)
{
Book bk;
bk.serializeBookVectorDemo(atoi(argv[1]));
// bk.deserializeBook(argv[1]);
cout << bk.getTimeNow2() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
free(Book::uuidValue);
}
 

 

 

Comile

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

cpp jsoncpp serialize anddeserialize complete example

 

 

 

 

Run

./h1 1000000

 

 

cpp jsoncpp serialize anddeserialize complete example

 

 

 

cpp jsoncpp serialize anddeserialize complete example

 

 

 

 

Deserialize

//main.cpp

#include "Model/Book.h"

int main(int args, char **argv)
{ 
   Book bk;
   // bk.serializeBookVectorDemo(atoi(argv[1]));
   bk.deserializeBook(argv[1]);
   cout << bk.getTimeNow2() << ",finished in " << __FUNCTION__ << "," << __LINE__ << endl;
   free(Book::uuidValue);
}

cpp jsoncpp serialize anddeserialize complete example

 

Compile

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

 

 

cpp jsoncpp serialize anddeserialize complete example

 

 

 

 

cpp jsoncpp serialize anddeserialize complete example

 

 

 

void Book::printBookVector(vector<Book> &vec)
{
    vector<Book>::iterator itr = vec.begin();
    while (itr != vec.end())
    {
        cout<<"idx=" <<itr->idx<<",id="<<itr->id << ",abstract=" << itr->abstract << ",author=" << itr->author << ",comment=" 
        << itr->comment << ",content=" << itr->content << ",name=" << itr->name << ",summary=" << itr->summary 
        << ",title=" << itr->title << ",topic=" << itr->topic << endl<<endl;
        free(itr->abstract);
        free(itr->author);
        free(itr->comment);
        free(itr->content);
        free(itr->name);
        free(itr->summary);
        free(itr->title);
        free(itr->topic);
        itr++;
    }
    cout << getTimeNow2() << ",finished in " << __FUNCTION__ << endl;
}

void Book::deserializeBook(const string &fileName)
{
    // fstream readFile(fileName, ios::in);
    string jsonValue = readFile(fileName);
    vector<Book> vec;
    Json::Reader jReader;
    Json::Value jsonRoot;
    if (jReader.parse(jsonValue, jsonRoot))
    { 
        for (Json::Value::iterator itr = jsonRoot.begin(); itr != jsonRoot.end(); itr++)
        { 

Book bk; bk.abstract = (char *)malloc(40); bk.author = (char *)malloc(40); bk.comment = (char *)malloc(40); bk.content = (char *)malloc(40); bk.name = (char *)malloc(40); bk.summary = (char *)malloc(40); bk.title = (char *)malloc(40); bk.topic = (char *)malloc(40); bk.idx = (*itr)["idx"].asUInt64(); bk.id=(*itr)["id"].asUInt64(); strcpy(bk.abstract, (char *)((*itr)["abstract"].asCString())); strcpy(bk.author, (char *)((*itr)["author"].asCString())); strcpy(bk.comment, (char *)((*itr)["comment"].asCString())); strcpy(bk.content, (char *)((*itr)["content"].asCString())); strcpy(bk.summary, (char *)((*itr)["summary"].asCString())); strcpy(bk.title, (char *)((*itr)["title"].asCString())); strcpy(bk.topic, (char *)((*itr)["topic"].asCString())); vec.push_back(bk); } } printBookVector(std::ref(vec)); cout << getTimeNow2() << ", finished in " << __FUNCTION__ << endl; }

 

Compile

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

 

Run

./h1 20221217191457911.txt

 

cpp jsoncpp serialize anddeserialize complete example

 

原文链接: https://www.cnblogs.com/Fred1987/p/16989262.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    cpp jsoncpp serialize anddeserialize complete example

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/401203

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月19日 上午9:10
下一篇 2023年4月19日 上午9:10

相关推荐