本篇内容主要讲解“C++怎么用jsoncpp库实现写入和读取json文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++怎么用jsoncpp库实现写入和读取json文件”吧!
一、jsoncpp库
我们都知道由于Json语法是 JavaScript 对象表示语法的子集。所以在Java,JavaScript等语言中使用起来是十分愉快的。在C++中我们使用跨平台的开源库JsonCpp也能愉快的玩耍Json。
JsonCpp 是一个C++库,允许操作 JSON 值,包括序列化和反序列化到字符串和从字符串反序列化。它还可以在非序列化/序列化步骤中保留现有注释,使其成为存储用户输入文件的便捷格式。
jsoncpp常用类
1.Json::Value
Json::Value:可以表示所有支持的类型,如:int , double ,string , object, array等。其包含节点的类型判断(isNull,isBool,isInt,isArray,isMember,isValidIndex等),类型获取(type),类型转换(asInt,asString等),节点获取(get,[]),节点比较(重载<,<=,>,>=,==,!=),节点操作(compare,swap,removeMember,removeindex,append等)等函数。
2.Json::Reader
Json::Reader:将文件流或字符串创解析到Json::Value中,主要使用parse函数。Json::Reader的构造函数还允许用户使用特性Features来自定义Json的严格等级。
3.Json::Writer
Json::Writer:与JsonReader相反,将Json::Value转换成字符串流等,Writer类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter(将数据写入一行,没有格式),Json::StyledWriter(按json格式化输出,易于阅读)。
Json::Reader可以通过对Json源目标进行解析,得到一个解析好了的Json::Value,通常字符串或者文件输入流可以作为源目标。
二、json文件
{
    "Address" : "北京",
    "Color" : [ 0.80000000000000004, 1.0, 0.5 ],
    "Date" : 1998,
    "Info" : 
    {
        "Class" : "三年级",
        "Part" : "西城区",
        "School" : "北京一中"
    },
    "Students" : 
    [
        {
            "Id" : 1,
            "ontime" : true,
            "sex" : "男",
            "time" : "2021-01-16"
        },
        {
            "Id" : 2,
            "ontime" : true,
            "sex" : "男",
            "time" : "2021-01-16"
        }
    ],
    "baseType" : "学校"
}三、读写json文件
// jsoncppTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
#include "json/json.h"
// 写入json文件
void CreateJsonFile()
{
    std::string strFilePath = "test.json";
    Json::Value root;
    root["Address"] = "北京";
    root["baseType"] = "学校";
    root["Date"] = 1998;
    root["Info"]["School"] = "北京一中";
    root["Info"]["Part"] = "西城区";
    root["Info"]["Class"] = "三年级";
                 
    root["Color"].append(0.8); 
    root["Color"].append(1.0);
    root["Color"].append(0.5);
    for (int i = 0; i < 2; i++)
    {
        root["Students"][i]["Id"] = i+1;    
        root["Students"][i]["sex"] = "男"; 
        root["Students"][i]["ontime"] = true;
        root["Students"][i]["time"] = "2021-01-16";
    }
    Json::StyledStreamWriter streamWriter;
    ofstream outFile(strFilePath);
    streamWriter.write(outFile, root);
    outFile.close();
    std::cout << "json文件生成成功!" << endl;
}
// 读取json文件
void ReadJsonFile()
{
    std::string strFilePath = "test.json";
    Json::Reader json_reader;
    Json::Value rootValue;
    ifstream infile(strFilePath.c_str(), ios::binary);
    if (!infile.is_open())
    {
        cout << "Open config json file failed!" << endl;
        return;
    }
    if (json_reader.parse(infile, rootValue))
    {
        string sAddress = rootValue["Address"].asString();
        cout << "Address = " << sAddress << endl;
        int nDate = rootValue["Date"].asInt();
        cout << "Date = " << nDate << endl;
        cout << endl;
        string sSchool = rootValue["Info"]["School"].asString();
        cout << "School = " << sSchool << endl;
        cout << endl;
        Json::Value colorResult = rootValue["Color"];
        if (colorResult.isArray())
        {
            for (unsigned int i = 0; i < colorResult.size(); i++)
            {
                double dColor = colorResult[i].asDouble();
                cout << "Color = " << dColor << endl;
            }
        }
        cout << endl;
        // 读取值为Array的类型
        Json::Value studentResult = rootValue["Students"];  
        if (studentResult.isArray())
        {
            for (unsigned int i = 0; i < studentResult.size(); i++)
            {
                int nId = studentResult[i]["Id"].asInt();
                cout << "Id = " << nId << endl;
                string sTime = studentResult[i]["time"].asString();
                cout << "Time = " << sTime << endl;
            }
        }
    }
    else
    {
        cout << "Can not parse Json file!";
    }
    infile.close();
}
int main()
{
    //CreateJsonFile();
    ReadJsonFile();
    return 0;
}