【3rdparty-AJson】系列

AJson

官方文档路径:
https://gitee.com/lordoffox/ajson

特点是:
ajson反序列化扫描的时候,直接将字面量类型同时解析,并将结果直接存入对应的数据结构字段。

如此一来就不需要临时的DOM,减少了中间处理的工作以及内存的申请释放,大大提升了性能。

使用方式简单,只要定义相应的宏AJSON,便可方便的序列化/反序列化操作。

依赖小,完全不依赖第三方库,只有一个头文件,省去了编译的麻烦。

使用实例

由于Ajson使用起来十分简便,故一章文章足以介绍其使用。
Json字符串转成数据结构

#include <iostream>
#include <string>

#include "ajson.hpp"

using namespace std;
using namespace ajson;

struct demo
{
  string hello;
  string world;
};

AJSON(demo,hello,world) //AJSON声明结构以及需要序列化的成员变量

int main(int argc, char * argv[])
{
    char * buff = "{\"hello\" : \"Hello\", \"world\" : \"world.\"}";
    demo the_demo;
    load_from_buff(the_demo,buff);
    cout << the_demo.hello << " " << the_demo.world << std::endl;
    cin.get();
    return 0;
}

结构体序列化和文件保存读取示例:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "ajson.hpp"

using namespace std;
using namespace ajson;

struct Education
{
    string  School;
    double  GPA;

    Education():GPA(0.0){}

    Education(const string& school , double gpa)
        :School(school),GPA(gpa)
    {
    }
};

struct Person
{
    string  Name;
    int         Age;
    vector<Education> Educations;
};

AJSON(Education , School , GPA)
AJSON(Person, Name , Age , Educations)

int main(int argc, char * argv[])
{
    Person person;
    person.Name = "Bob";
    person.Age = 28;
    person.Educations.push_back(Education("MIT",600));
    string_stream ss;
    save_to(ss,person);
    std::cout << ss.str() << std::endl;
    //保存到文件
    save_to_file(person, "./out.json");

    //从Json加载
    Person p;
    load_from_buff(p, ss.str().data());

    //从文件加载
    Person p2;
    load_from_file(p2, "./out.json");

    cin.get();
    return 0;
}

打印如下:
这里写图片描述
文件如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/gx864102252/article/details/81431021