首页 > 其他分享 >Jsoncpp的使用

Jsoncpp的使用

时间:2023-11-15 19:44:42浏览次数:29  
标签:const Jsoncpp value json bool Value 使用 root

目录

动态库和静态库

生成

https://github.com/open-source-parsers/jsoncpp

下载后通过cmake生成vs项目

生成后得到vs项目

打开sln文件之后,右键jsoncpp lib,生成lib和dll文件

lib在/lib/Debug下,dll在/bin/Debug下
这里的lib相当于一个.h,dll是.cpp,因此配合使用,

Jsoncpp的使用

jsoncpp库中的类被定义到了一个Json命名空间中,建议在使用这个库的时候先声明这个命名空间:

using namespace Json;

使用jsoncpp库解析json格式的数据,我们只需要掌握三个类:

  1. Value 类:将json支持的数据类型进行了包装,最终得到一个Value类型
  2. FastWriter类:将Value对象中的数据序列化为字符串
  3. Reader类:反序列化, 将json字符串 解析成 Value 类型

value类

枚举类型 说明 翻译
nullValue ‘null’ value 不表示任何数据,空值
intValue signed integer value 表示有符号整数
uintValue unsigned integer value 表示无符号整数
realValue double value 表示浮点数
stringValue UTF-8 string value 表示utf8格式的字符串
booleanValue bool value 表示布尔数
arrayValue array value (ordered list) 表示数组,即JSON串中的[]
objectValue object value (collection of name/value pairs) 表示键值对,即JSON串中的{}

构造函数

// 因为Json::Value已经实现了各种数据类型的构造函数
Value(ValueType type = nullValue);
Value(Int value);
Value(UInt value);
Value(Int64 value);
Value(UInt64 value);
Value(double value);
Value(const char* value);
Value(const char* begin, const char* end);
Value(bool value);
Value(const Value& other);
Value(Value&& other);

检测保存的数据类型

// 检测保存的数据类型
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isInt64() const;
bool isUInt() const;
bool isUInt64() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const;
bool isObject() const;

将value对象转换为实际类型

Int asInt() const;
UInt asUInt() const;
Int64 asInt64() const;
UInt64 asUInt64() const;
LargestInt asLargestInt() const;
LargestUInt asLargestUInt() const;
JSONCPP_STRING asString() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
const char* asCString() const;

对json数组的操作

ArrayIndex size() const;
Value& operator[](ArrayIndex index);
Value& operator[](int index);
const Value& operator[](ArrayIndex index) const;
const Value& operator[](int index) const;
// 根据下标的index返回这个位置的value值
// 如果没找到这个index对应的value, 返回第二个参数defaultValue
Value get(ArrayIndex index, const Value& defaultValue) const;
Value& append(const Value& value);
const_iterator begin() const;
const_iterator end() const;
iterator begin();
iterator end();

对json对象的操作

Value& operator[](const char* key);
const Value& operator[](const char* key) const;
Value& operator[](const JSONCPP_STRING& key);
const Value& operator[](const JSONCPP_STRING& key) const;
Value& operator[](const StaticString& key);

// 通过key, 得到value值
Value get(const char* key, const Value& defaultValue) const;
Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
Value get(const CppTL::ConstString& key, const Value& defaultValue) const;

// 得到对象中所有的键值
typedef std::vector<std::string> Members;
Members getMemberNames() const;

将Value对象数据序列化为string

// 序列化得到的字符串有样式 -> 带换行 -> 方便阅读
// 写配置文件的时候
std::string toStyledString() const;

fastwriter类

// 将数据序列化 -> 单行
// 进行数据的网络传输
std::string Json::FastWriter::write(const Value& root);

reader类

bool Json::Reader::parse(const std::string& document,
    Value& root, bool collectComments = true);
    参数:
        - document: json格式字符串
        - root: 传出参数, 存储了json字符串中解析出的数据
        - collectComments: 是否保存json字符串中的注释信息

// 通过begindoc和enddoc指针定位一个json字符串
// 这个字符串可以是完成的json字符串, 也可以是部分json字符串
bool Json::Reader::parse(const char* beginDoc, const char* endDoc,
    Value& root, bool collectComments = true);
	
// write的文件流  -> ofstream
// read的文件流   -> ifstream
// 假设要解析的json数据在磁盘文件中
// is流对象指向一个磁盘文件, 读操作
bool Json::Reader::parse(std::istream& is, Value& root, bool collectComments = true);

VS的配置


简单的示例代码

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

using namespace std;
using namespace Json;
/*示例数据
[
    12, 
    true, 
    "tom", 
    ["jack", "ace", "robin"], 
    {"sex":"man", "girlfriend":"lucy"}
]
*/

void writeJson()
{
	Value root;
    root.append(12);
    root.append(true);
    root.append("tom");
    //创建一个子数组
    Value subArray1;
    subArray1.append("jack");
    subArray1.append("ace");
    subArray1.append("robin");
    root.append(subArray1);
    //创建一个子对象
    Value subObj;
    subObj["sex"] = "man";
    subObj["girlfriend"] = "lucy";
    root.append(subObj);

#if 1
    string json = root.toStyledString();
#else
    FastWriter w;
    string json = w.write(root);
#endif
    //写入文件
    ofstream ofs("test.json");
    ofs << json;
    ofs.close();

}

void readJson()
{
    //打开文件
    ifstream ifs("test.json");
    Reader r;
    Value root;
    //用reader解析并导入root中
    r.parse(ifs, root, true);
    if (root.isArray())
    {
        for (int i = 0; i < root.size(); i++)
        {
            Value item = root[i];
            //如果是int类型,就变成it输出
            if (item.isInt())
            {
                cout << item.asInt() << endl;
            }
            else if (item.isString())
            {
                cout << item.asString() << endl;
            }
            else if (item.isBool())
            {
                cout << item.asBool() << endl;
            }
            else if (item.isArray())
            {
                for (int j = 0; j < item.size(); j++)
                {
                    cout << item[j].asString() << endl;
                }
            }
            else if (item.isObject())
            {
                Value::Members keys = item.getMemberNames();
                for (int j = 0; j < keys.size(); j++)
                {
                    cout << keys.at(j) << " : " << item[keys[j]] << endl;
                }
            }
        }
    }
}

int main()
{
    writeJson();
    readJson();
    return 0;
}

标签:const,Jsoncpp,value,json,bool,Value,使用,root
From: https://www.cnblogs.com/liviayu/p/17834620.html

相关文章

  • 使用js判断颜色是否相等,然后投票
    首先做出来的效果图是这样的代码如下<divclass="hua_zdm_15"id="toupiao"><divclass="hua_zd_00_z"onclick="zd_change(0)">涨</div><divclass="hua_zd_00_dm_20"onclick="zd_change(1)">跌&......
  • bcmath相关函数使用
    ubuntu 安装bcmath插件sudoapt-getinstallphp7.0-bcmathcentos安装yuminstallphp72w-bcmathwindows版本的php自带,无需另外安装函数的使用//bcscale—设置所有bc数学函数的默认小数点保留位数bcscale(3);//返回布尔型true不指定位数,下面默认为保留小数3位$a='6......
  • 使用Cmake创建一个head only的库(未完待续)
    IntheCMakescriptyouprovided,thesecondparameteroftheadd_library()functionisanemptystring"".ThisisacommonpatternusedinCMaketocreatean"interface-only"libraryoraheader-onlylibrary.以下是示例add_library(conve......
  • ASP.Net MVC使用特性路由
    ASP.NETMVC中使用特性路由需要在默认路由前调用routes.MapMvcAttributeRoutes();需要注意Action上使用特性路由时需要注意不能以/开头不能写成/Controller/Action如果使用了routes.MapMvcAttributeRoutes();出现不能调用控制器“xx”上的操作方法“xx”,因为该方法是一种泛......
  • ABAP使用异步远程RFC实现并行处理
    1、使用场景当开发复杂报表,需要处理大量数据,不管怎么优化计算和查询语句,程序的运行效率还是达不到用户要求,怎么办?为了解决这个问题,就需要程序实现并行处理。本文档就是通过异步调用远程RFC的办法,实现对大量数据的计算,以并行的方式,更快的计算出最终结果。2、代码实现在实现并......
  • Lombok使用详解
    https://blog.csdn.net/u010695794/article/details/70441432?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170003157816800215083138%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=170003157816800215083138&biz_id=0&......
  • 软件测试|Python openpyxl库使用指南
    简介我们之前介绍过,python在自动化办公方面可以大放异彩,因为Python有许多的第三方库,其中有很多库就支持我们对office软件进行操作,熟练的使用Python对office进行操作,可以实现自动化办公,极大提升我们的工作效率。本篇文章,我们就来介绍一下处理Excel的第三方库,openpyxl的使用。安......
  • 一个Git clone仓库的指定目录命令对比国内外常见AI(一)使用ChatGPT3.5
    通常情况下,我们会克隆整个Git仓库,但有时候我们只需要其中某一个目录或文件,这时候只克隆子目录会更加方便。这个需求好像不是经常用到,搜索结果也是五花八门,有些完全达不到要求,正好用这个机会测试一下最近大火的AI看看是否足够智能。国外ChatGPT3.5(找一个可以访问的就好,ChatGPT4没找......
  • Linux下make工具的使用
    环境:Ubuntu18.04.6文章参考:爱编程的大丙(subingwen.cn)简介:gcc命令可以帮助我们编译源文件,但当源文件数量多到一定程度时,使用gcc命令就会变得较为复杂。项目构建工具make应运而生,make是一个命令工具,用于解释makefile中指令的命令工具。在构建项目时,make工具会自动加载当......
  • template使用
    template语法template<typenameT>类/函数的实现注意:typename可以指定int,float等内置数据类型,自定义的class模板只有再使用的时候才会定义模板的定义不能与标准库冲突template用法重载的时候//打印不同的数据类型//print(5)//print(5.0f)//print("helloworld!")......