有用的JsonCpp的使用

1、JsonCpp
C++库,允许操作JSON值,包括与字符串串行化和序列化。它可在反序列化/序列化步骤中保留现有注释,使其成为存储用户输入文件的便捷方式。是一个第三方JSON解析库,可将源码编译成方便使用动态链接库、静态链接库或者静态导入库的。jsconcpp 进行 JSON 解析的源码文件分布在 include/json、src/lib_json 下。
JsonCpp(1.8.4版本):https://github.com/open-source-parsers/jsoncpp/tree/1.8.4

2、JsonCpp编译工具
(1)Cmake
一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的automake。Cmake 并不直接建构出最终的软件,而是产生标准的建构档(如 Unix 的 Makefile 或 Windows Visual C++ 的 projects/workspaces),然后再依一般的建构方式使用。
(2)Mesos
scons:Python写的自动化构建工具,是一个更简便,更可靠,更高效的编译软件,可用于编译jsoncpp。
(3)Doxygen
用于带注释的C++源生成文档的事实上的标准工具。程序的文件产生工具,可将程序中的特定注释转换为说明文件。能依据程序本身的结构,将注释经过处理重新整理成为一个纯粹的参考手册。
3、JsonCpp编译
除了使用以上工具编译外,还可以使用visual studio编译。
(1)用VS打开jsoncpp-1.8.4\makefiles\vs71 /jsoncpp.sln 便可以开始编译。
(2)打开vs2013 点击项目lib_json右键-属性-C/C++ -代码生成 选择多线程调试(MTD)
(3)调试修改为 debug右键按下鼠lib_json 选择生成,则在jsoncpp-1.8.4\build\vs71\debug\lib_json生成json_vc71_libmtd.lib(注意最后为libmtd)。vs2013自动编译项目。(如果为release,则相对于生成releas版本为json_vc71_libmt.lib(最后为libmt))

(4)编译后在jsoncpp-1.8.4\build\vs71\release\lib_json找到json_vc71_libmtd.lib将其复制到vs工程的的lib里(即直接复制到项目中)

(5)在项目中右击—配置—配置属性—C/C++ --代码生成—运行库—多线程(/MTD)(注意与上面的lib的生成版本有关,要改为对应的形式)

(6)在项目中右击—配置—配置属性链接器–输入—附加依赖项,最后添加json_vc71_libmtd.lib,(或者在cpp源代码添加#pragma comment(lib, “json_vc71_libmtd.lib”))

(7)将jsoncpp的头文件include复制到vs的include.,并在项目中引入,然后就可以使用了

4、JsonCpp基础
jsonCpp主要包含三种类型的class:value、reader、write。jsonCpp总所有对象、类名都在namespace json中,使用时只要包含json.h即可。
(1)Json::Value
Json::Value时jsonCpp中最基本、最重要的类,用于表示各种类型的对象,jsoncpp 支持的对象类型可见 Json::ValueType 枚举值
例:

Json::Value root;
root["status"] = 1;            //新建一个key为status,赋予数值1
root["message"] = "OK";        //新建一个key为message,赋予字符串OK
root["array"].append("arr"); //新建一个key为array,类型为数组,对第一个元素赋值为字符串“arr”
root["array"].append(1234);  // 为数组 key_array 赋值,对第二个元素赋值为:1234。
Json::ValueType type = root.type();    //获得root的类型

注:a、跟C++ 不同,JavaScript 数组可以为任意类型的值,所以 jsoncpp 也可以。
jsoncpp 还有一些其他同能,比如说设置注释、比较 json 大小、交换 json 对象等
b、在把value插入值后再输出来,输出的值是按字母表的顺序排列。
c、Json::ValueType:value的类型,是一个枚举型

enum ValueType {
  nullValue = 0, ///< 'null' value
  intValue,      ///< signed integer value
  uintValue,     ///< unsigned integer value
  realValue,     ///< double value
  stringValue,   ///< UTF-8 string value
  booleanValue,  ///< bool value
  arrayValue,    ///< array value (ordered list)
  objectValue    ///< object value (collection of name/value pairs).
};

(2)Json::Writer
a、Json::Writer负责将内存中的Value对象转换成JSON文档,输出文件或者是字符串中。
b、Json::Writer是一个纯虚类,不能直接使用,一般使用Json::Writer的子类:Json::FasterWriter, Json::StyledWriter、Json::StyledStreamWriter
注:在新版中Json::FasterWriter, Json::StyledWriter、Json::Reader都被弃用,替代的是Json::StreamWriterBuilder、Json::CharReaderBuilder
c、Json::FasterWriter:速度最快
d、Json::StyledWriter:格式化后的json

(3)Josn::Reader
用于读取,准确说是用于将字符串或者文件输入流转换为Json::Value对象的。
parse()
a、使用Json::Reader对json文件进行解析
bool parse(const std::string& document, Value& root, bool collectComments = true);
参数:document: 包含要读取的文档的UTF-8编码字符串
root:(输出)Json::Value的对象

b、使用Json::Reader对json输入流(文件)进行解析
bool parse(std:stream& is, Value& root, bool collectComment = true);

c、使用Json::Reader对字符串进行解析
bool parse(const char* beginDoc, const char* ednDoc, Value& root, bool collectComment = true);

(4)JsonCpp其他操作
a、判断key是否存在
bool Json::Value::isMember ( const char * key) const;
存在返回1,否则返回0

b、判断是否为null成员函数
注:Json::Value和C++中的map有一个共同的特点,就是当你尝试访问一个不存在的 key 时,会自动生成这样一个key-value认为null的值对。

c、得到所有成员
typedef std::vectorstd::string Json::Value::Members;
Value::Members Json::Value::getMemberNames ( ) const;
函数的类型为一个string的vector。

d、删除成员
Value Json::Value::removeMember( const char* key)
返回删除的值,或者null

5、测试实例

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

using namespace std;

int main()
{
    const char* age;
    Json::Value root;
    Json::FastWriter fast_writer;
    Json::StyledWriter style_writer;
    Json::StyledStreamWriter stream_writer;
    Json::Reader reader;
    Json::Value json_object;

    root["null"] = NULL;            //注意此处在输出显示为0,而非null
    root["message"] = "OK";
    root["age"] = 52;
    root["array"].append("arr");    // 新建一个key为array,类型为数组,对第一个元素赋值为字符串“arr”
    root["array"].append(123);        // 为数组 key_array 赋值,对第二个元素赋值为:1234

    Json::ValueType type = root.type();                //root的类型

    cout << root.toStyledString() << endl;            //格式化输出
    cout << "root_type:" <<type << endl;            //类型为7,即为类型为对象

    // 写到本地文件
    cout << "快速输出:" << endl;
    string str = fast_writer.write(root);
    cout << str << endl;        //快速输出,紧凑型
    ofstream ofs("fast_writer.json");
    ofs << str;
    ofs.close();

    cout << "格式化输出:" << endl;
    str = style_writer.write(root);
    cout << str << endl;        //格式化输出,排版型
    ofs.open("style_writer.json");
    ofs << str;
    ofs.close();


    // 对字符串解析
    //const char* json_document = "{\"age\" : 12, \"name\" : \"weng\"}";
    string json_document = "{\"age\" : 123, \"name\" : \"weng\"}";
    if (!reader.parse(json_document, json_object)){
        cout << "error" << endl;
        return 0;
    }
    else{
        cout <<"age:" <<json_object["age"] << " name" << json_object["name"] << endl;
    }
    
    // 对文件解析
    ifstream ifs("E:\\demo\\JsonTest\\JsonTest\\example.json", ios::binary);
    if (!reader.parse(ifs, json_object)){
        cout << "open error" << endl;
        ifs.close();
    }else{
        cout << "encoding:" << json_object["encoding"].asstring() << endl;
        cout << "age:" <<json_object["age"].asInt() << endl;
        int num = json_object["plug"].size();
        for (int i = 0; i < num; i++){
            cout << json_object["plug"][i].asstring() << " ";
        }
        ifs.close();
        cout << endl;
    }

    // 判断key是否存在
    bool is_age =  root.isMember("age");
    cout << "isMember:" <<is_age << endl;

    // 判断是否为null
    //bool is_null = root["null"].isNull();            //注意此处被赋值为0,而非null
    bool is_null = json_object["null"].isNull();
    cout << "is_null:" << is_null << endl;

    // 得到所有的key
    for (auto elem : root.getMemberNames()){
        cout << elem << " ";
    }
    cout << endl;

    // 删除成员
    cout << "remove_age:" << root.removeMember("age") << endl;


    system("pause");
    return 0;
}
————————————————
版权声明:本文为CSDN博主「king_weng」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/King_weng/article/details/88430199

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...
win11本地账户怎么改名?win11很多操作都变了样,用户如果想要...