【C++】Json库介绍和使用

JsonCpp库

Json数据格式

Json 是一种数据交换格式,它采用完全独立于编程语言的文本格式来存储和表示数据。

例如:我们想表示一个同学的学生信息

C代码表示

cpp 复制代码
char *name = "xx";
int age = 18;
float score[3] = {88.5,99,58];

Json表示

cpp 复制代码
{
    "姓名" : "xx",
    "年龄" : 18,
    "成绩" : {88.5,99,58},
    "爱好" : {
        "书籍" : "西游记",
        "运动" : "打游戏"
    }
}

Json 的数据类型包括对象,数组,字符串,数字等

  • 对象:使用花括号 { } 括起来的表示一个对象
  • 数组:使用中括号 亏括起来的表示一个数组
  • 字符串:使用常规双引号 " " 括起来的表示一个字符串
  • 数字:包括整形和浮点型,直接使用

Jsoncpp介绍

Jsoncpp 库主要是用于实现 Json 格式数据的序列化和反序列化,它实现了将多个数据对象组织成为 Json 格式字符串,以及将 Json 格式字符串解析多个数据对象的功能

先看一下 Json 对象类的表示

cpp 复制代码
class Json::Value {
    Value &operator=(const Value &other); // Value重载了[]和=,因此所有的赋值和获取数据都可以通过
    Value& operator[](const std::string& key); // 简单的方式完成 val["name"] = "xx";
    Value& operator[](const char* key);
    Value removeMember(const char* key); // 移除元素
    const Value& operator[](ArrayIndex index) const; // val["score"][0]
    Value& append(const Value& value); // 添加数组元素 val["score"].append(88);
    ArrayIndex size() const; // 获取数组元素个数 val["score"].size();
    std::string asString() const; // 转string string name = val["name"].asString();
    const char* asCString() const; // 转char* char *name = val["name"].asCString();
    Int asInt() const; // 转int int age = val["age"].asInt();
    float asFloat() const; // 转float float weight = val["weight"].asFloat();
    bool asBool() const; // 转 bool bool ok = val["ok"].asBool();
};

Jsoncpp 主要借助三个类以及对应的少量成员函数完成序列化和反序列化

1.序列化接口

cpp 复制代码
class JSON_API StreamWriter {
    virtual int write(Value const& root, std::ostream* sout) = 0;
}
class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
    virtual StreamWriter* newStreamWriter() const;
}

2.反序列化接口

cpp 复制代码
class JSON_API CharReader {
    virtual bool parse(char const* beginDoc, char const* endDoc, 
                       Value* root, std::string* errs) = 0;
}
class JSON_API CharReaderBuilder : public CharReader::Factory {
    virtual CharReader* newCharReader() const;
}

Jsoncpp 使用

cpp 复制代码
#include <iostream>
#include <sstream>
#include <string>
#include <jsoncpp/json/json.h>
#include <memory>

// 实现数据的序列化
bool serialize(const Json::Value &val, std::string &body)
{
    
    std::stringstream ss;
    // 先实例化一个工厂类对象
    Json::StreamWriterBuilder swb;

    swb["emitUTF8"] = true; 

    // 通过工厂类对象来生产派生类对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val, &ss);

    if(ret != 0){
        std::cout << "Json serialize failed!\n";
        return false;
    }

    // std::cout << std::endl;
    body = ss.str();
    return true;
}

// 实现json字符串的反序列化
bool unserialize(const std::string &body, Json::Value &val)
{
    // 实例化工厂类对象
    Json::CharReaderBuilder crb;
    // 生产CharReader对象
    std::string errs;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if(ret == false){
        std::cout << "json unserialize failed : " << errs <<std::endl;
        return false;
    }
    return true;
}

int main()
{

    const char *name = "小明";
    int age = 18;
    const char *sex = "男";
    float score[3] = {88, 77.5, 66};

    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);

    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "打篮球";
    student["爱好"] = fav;
    std::string body;
    serialize(student, body);
    std::cout << body << std::endl;

    std::string str = R"({"姓名":"小黑", "年龄":19, "成绩":[32, 45, 56]})";
    Json::Value stu;
    bool ret = unserialize(str,stu);
    if(ret == false) return -1;
    std::cout << "姓名: " << stu["姓名"].asString() << std::endl;
    std::cout << "年龄: " << stu["年龄"].asInt() << std::endl; 
    int sz = stu["成绩"].size();
    for(int i = 0;i < sz; i++){
        std::cout << "成绩: " << stu["成绩"][i].asFloat() << std::endl;
    }

    return 0;
}
相关推荐
重生之小比特1 小时前
【C++进阶】map和set
java·开发语言·c++
知识分享小能手2 小时前
C++ 学习教程,从入门到精通,C++对象和类 — 详细知识点总结(10)
开发语言·c++·学习
顺顺 尼2 小时前
linux 进程信号(上)
linux·c++·算法
海上小飞龙4 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
java·c++·python
Persistent的粽子!4 小时前
双指针算法:最大盛水容器
c++·算法·leetcode
小小龙学IT4 小时前
三菱 PLC MC 协议(SLMP / QnA 兼容 3E 帧)深度解析:从帧结构到 C++/Go 双语言采集实战
c语言·c++·golang
程序猿编码4 小时前
C++/CUDA 手写 LLM 推理引擎:拆解 vLLM 核心 PagedAttention 与连续批处理
开发语言·c++·深度学习·神经网络·推理·vllm
hold?fish:palm5 小时前
44 二叉搜索树中第K小的元素
开发语言·c++·算法
凉茶钱5 小时前
【吃透C++】万字解析类和对象
开发语言·c++