Jsoncpp学习

一.Jsoncpp定义

jsoncpp 是一个 C++ 库,允许操作 JSON 值,包括字符串之间的序列化和反序列化。它还可以在反序列化/序列化步骤中保留现有注释,使其成为存储用户输入文件的方便格式

其主要基于三个类实现上面内容,下面我们来学习下这三个类。



二.Jsoncpp类

头文件:#include <json/json.h>

三个类分别为:

1.Josn::Value:

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();
};

作用:可以表示所有支持的类型,如:int , double ,string , object, array等。其包含节点的类型判断(isNull,isBool,isInt,isArray,isMember,isValidIndex等),类型获取(type),类型转换(asInt,asString等),节点获取(get,[]),节点比较(重载<,<=,>,>=,==,!=),节点操(compare,swap,removeMember,removeindex,append等)等函数

2.Json::Reader:

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;
}

作用:将文件流或字符串创解析到Json::Value中,主要使用parse函数。Json::Reader的构造函数还允许用户使用特性Features来自定义Json的严格等级

3.Json::Writer:

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;
}

作用:与JsonReader相反,将Json::Value转换成字符串流等,Writer类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter(将数据写入一行,没有格式),Json::StyledWriter(按json格式化输出,易于阅读)



三.Jsoncpp实例

例一:

假设我们现在有一个one.json文件,内容如下:

{
    "name":"zhangsan",
    "age":18
}

现在我们jsoncpp来讲one.json文件内容通过Reader解析到Value;

#include <iostream>
#include <json/json.h>
#include <fstream>
#include <assert>

void test_1()
{
    //1.从文件one.json中
    std::ifstream ifs;
    ifs.open("./one.json");//假设路径
    //2.检查打开情况
    assert(ifs.is_open());
    //3.创建类对象开始解析
    Json::Reader reader;
    Josn::Value root;
    if(!reader.parse(ifs,root,false))
    {
        //解析失败
        std::cout<<"parse error"<<std::endl;
        return;
    }
    //成功解析
    string name=root["name"].asString();
    int age=root["age"].asInt();
    //4.输出:
    std::cout<<"name= "<<name<<" "<<"age= "<<age<<std::endl;
    return 0;
}
        
    
int main()
{
    test_1();
    return 0;
}

例二:

我们将一个json对象解析打印

#include <iostream>
#include <json/json.h>
#include <string>

void test_2()
{
    //1.创建j送对象,模拟
    const char json_data[] =
            "{\"name\" : \"Tocy\", \"salary\" : 100, \"msg\" : \"work hard\"};
    //{"name" : "tony", "salary" : 100, "msg" : "work hard"}
    //2.创建jsoncpp对象
    Json::Value root;
    Json::Reader reader;
    //3.检查解析
    if(!reader.parse(json_data,json_data+sizeof(json_data),root))
    {
        //解析失败
        std::cout<<"parse error"<<std::endl;
        return;
    }
    //4.将Value对象中打印
    string name=root["name"].asString();
    int salary=root["salart"].asInt();
    string msg=root["msg"].asString();
    //5.打印:
    std::cout << "name: " << name << "  "<< salary: " << salary;
    std::cout<<" msg: " << msg <<std::endl;
    return;
}
int main()
{
    test_2();
    return 0;
}

例三:

解析json数组

#include <iostream>
#include <json/json.h>
#include <string>


void test_3()
{
    //1.创建json数组
    const char json_data[] =
		"[{\"name\" : \"Tocy\", \"salary\" : 100}, {\"name\" : \"Kit\", \"salary\" : 89}]";
    //[{"name":"jack","salary":100}, {"name":"kit","salary":89}]
    //2.创建josncpp对象
    Json::Value root;
    Json::Reader reader;
    //3.解析
    if(!reader.parse(json_data,json_data+sizeof(json_data),root))
    {
        //解析失败
        std::cout<<"parse error"<<std::endl;
        return;
    }
    //4.拷贝打印
    int count = root.size();
    for(int i=0;i<count;i++)
    {
        string name=root[i]["name"].asString();
        int salary=root[i]["age"].asInt();
        std::cout<<"name: "<<name<<" " <<"age: "<<age<<std::endl;
    }
    return;
}    
int main()
{
    test_3();
    return 0;
}

例四:

将Value内容整体以字符串方式打印

#include <iostream>
#include <json/json.h>
#include <string>

void test_4()
{
    //1.创建对象
    Json::Value root;
    Json::Writer writer;
    Josn::Value kidroot;
    //2.将kidroot中填充内容(也可以直接用root,这里是为了演示
    kidroot["name"] = "tony";
	kidroot["age"] = 22;
    root.append(kidroot);//将kidroot中内容追加到root中
    //3.将root中内容转换为字符串
    string jsonstr=writer.write(root);//json-> 字符串
    //4.打印
    std::cout<<jsonstr<<std::endl;
    //结果:[{"age":22,"name":"tony"}]  注意:逆序打印
    return;
}
    
   
int main()
{
    test_4();
    return 0;
}

例五;

将含有数组的Value对象以字符串方式打印

#include <iostream>
#include <json/json.h>
#include <string>


void test_5()
{
    //1.创建对象
    Json::Value root;
    Json::Value files;//kidroot
    Json::Writer writer;
    root["name"] = "tocy";
	root["salary"] = 100;
	root["msg"] = "work hard";

    //2.将kidroot中填充数组
    files[0] = "1.ts";
	files[1] = "2.txt";
    //将kidroot拷贝如root
	root["files"] = files;
    
    //打印:
    std::string json_data = writer.write(root);
    std::cout<<json_data<<std::endl;
    //结果 {"files":["1.ts","2.txt"],"msg":"work hard","name":"tocy","salary":100}
    return;
}

int main()
{
    test_5();
    return 0;
}

例六:

将嵌套对象的json数组以字符串方式打印

#include <iostream>
#include <json/json.h>
#include <string>


void test_6()
{
    //1.创建Json对象
    Json::Value root;
    Json::Writer writer;
    // 使用{}只是为了隔离作用域
	{
		Json::Value person;
		person["name"] = "jack";
		person["salary"] = 200;
		// index start 0
		root[0] = person;
	}
	{
		Json::Value person;
		person["name"] = "miss";
		person["salary"] = 1000;
		//
		root[1] = person;
	}
    //2.将json对象转换为字符串
    string json_data = writer.write(root);
	std::cout << json_data << std::endl;
    return 0;
}
int main()
{
    test_6();
    return 0;
}

上面这些就够我们去实现序列化和反序列化

本文借鉴于:

jsoncpp的简易教程 - JindouBlog - 博客园 (cnblogs.com)

最后,感谢大家的支持!!!

猜你喜欢

转载自blog.csdn.net/2301_79813267/article/details/142899349