JSONCPP使用

安装

命令行安装

sudo apt-get update
sudo apt-get install libjsoncpp-dev

源代码安装(道理和安装其他包一样)

  1. 在github下载源代码

image.png

  1. 解压源代码
tar zxvf ./jsoncpp-1.9.5.tar.gz
  1. 建立build文件夹编译安装
cd json
mkdir build
cd build
cmake ..
make
sudo make install
  1. 最后更新系统库链接
ldconfig

介绍


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

using namespace Json;

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

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

Value类

枚举类型

  • 这个类可以看做是一个包装器,他可以封装json支持的所有类型,这样我们在处理数据的时候就方便多了。
    | 枚举类型 | 说明 | 翻译 |
    | — | — | — |
    | 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串中的{} |

构造函数

Value类为我们提供了很多构造函数,通过构造函数来封装数据,最终得到一个统一的类型。

// 因为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);

实际案例

使用jsoncpp序列化数据到磁盘

首先介绍文件组织结构:
image.png

  1. 编写src/CMakeLists.txt文件:
add_executable(json_str main.cpp)
target_link_libraries(json_str jsoncpp)
  1. 编写CMakeLists.txt文件:
project(json_str)

cmake_minimum_required(VERSION 3.10)
add_compile_options(-std=c++11)

find_package(jsoncpp REQUIRED)
if(jsoncpp_FOUND)
    message("found success!")
else()
    message("found fail")
endif()
include_directories(${jsoncpp_INCLUDE_DIRS})
link_libraries(${jsoncpp_LIBRARY})

add_subdirectory(src bin)
  1. 编写main.cpp测试程序
#include<iostream>
#include<string>
#include<fstream>
#include<jsoncpp/json/value.h>
#include<jsoncpp/json/writer.h>
#include<jsoncpp/json/reader.h>

/**
 [
    "luffy", 19, 170, false,
    ["ace", "sabo"],
    {"sex", "man", "girlfriend":"Hancock"}
 ]
*/

int main()
{
    std::cout << "hello world!" << std::endl;
    // 创建Value对象,作为json数组。
    Json::Value root;
    root.append("luffy");
    root.append(19);
    root.append(170);
    root.append(false);

    // 作为json数组中的json数组
    Json::Value brother;
    brother.append("ace");
    brother.append("sabo");

    // 创建Value对象,用于存放json字符串
    Json::Value love;
    love["sex"] = "man";
    love["girlfriend"] = "Hancock";

    root.append(brother);
    root.append(love);

    #if 0
        std::string json_str = root.toStyledString();
    #else
        Json::FastWriter writer;
        std::string json_str = writer.write(root);
    #endif

    // 将序列化后的数据写入磁盘文件
    std::ofstream  wo("../src/json_str.json");
    wo << json_str;
    wo.close();

    return 0;
}
  1. 测试结果(成功保存)

image.png

解析json字符串

和上边的程序只有main.cpp有区别:

#include<iostream>
#include<string>
#include<fstream>
#include<jsoncpp/json/value.h>
#include<jsoncpp/json/writer.h>
#include<jsoncpp/json/reader.h>

/**
 [
    "luffy", 19, 170, false,
    ["ace", "sabo"],
    {"sex", "man", "girlfriend":"Hancock"}
 ]
*/

void jsonparse(Json::Value& value)
{
    if(value.isArray())
    {
        std::cout << std::endl;
        for(int i=0; i<value.size(); ++i)
        {
            Json::Value temp = value[i];
            jsonparse(temp);
        }
    }else if(value.isString())
    {
        std::cout << value.asString() << " ";
    }else if(value.isInt())
    {
        std::cout << value.asInt() << " ";
    }else if(value.isBool())
    {
        std::cout << value.asBool() << " ";
    }else if(value.isObject())
    {
        std::cout << std::endl;
        Json::Value::Members keys = value.getMemberNames();
        for(int i=0; i<keys.size(); ++i)
        {
            std::cout << keys[i] << ":" << value[keys[i]] << std::endl;
        }
    }
}

int main()
{
    // std::cout << "hello world!" << std::endl;
    // 创建Value对象,作为json数组。
    Json::Value root;
    root.append("luffy");
    root.append(19);
    root.append(170);
    root.append(false);

    // 作为json数组中的json数组
    Json::Value brother;
    brother.append("ace");
    brother.append("sabo");

    // 创建Value对象,用于存放json字符串
    Json::Value love;
    love["sex"] = "man";
    love["girlfriend"] = "Hancock";

    root.append(brother);
    root.append(love);

    #if 0
        std::string json_str = root.toStyledString();
    #else
        Json::FastWriter writer;
        std::string json_str = writer.write(root);
    #endif

    // 将序列化后的数据写入磁盘文件
    std::ofstream  wo("../src/json_str.json");
    wo << json_str;
    wo.close();

    std::ifstream ri("../src/json_str.json");
    Json::Reader json_pasre;
    Json::Value json;
    json_pasre.parse(ri, json);
    // 调用解析函数进行打印
    jsonparse(json);

    return 0;
}

运行结果:
image.png

  • 26
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jsoncpp是一个C++ JSON解析库,它可以将JSON数据转换为C++对象,也可以将C++对象转换为JSON数据。 下面是Jsoncpp使用详解: 1. 下载安装 你可以从Jsoncpp的官方网站下载最新的源代码,然后编译安装。也可以使用包管理器进行安装,如在Ubuntu下可以使用以下命令进行安装: ``` sudo apt-get install libjsoncpp-dev ``` 2. 解析JSON数据 Jsoncpp提供了一个Json::Value类,它可以表示JSON数据中的任何类型。使用Jsoncpp解析JSON数据的一般步骤如下: ```c++ #include <iostream> #include <jsoncpp/json/json.h> int main() { std::string json_str = "{\"name\": \"Tom\", \"age\": 18}"; Json::Value root; Json::CharReaderBuilder builder; Json::CharReader* reader = builder.newCharReader(); JSONCPP_STRING errors; bool parsing_successful = reader->parse(json_str.c_str(), json_str.c_str() + json_str.size(), &root, &errors); delete reader; if (!parsing_successful) { std::cerr << "Failed to parse JSON: " << errors << std::endl; return -1; } std::string name = root["name"].asString(); int age = root["age"].asInt(); std::cout << "Name: " << name << ", Age: " << age << std::endl; return 0; } ``` 上面的代码解析了一个JSON字符串,然后获取了其中的"name"和"age"字段的值。 3. 生成JSON数据 Jsoncpp可以将C++对象转换为JSON数据。下面是一个示例: ```c++ #include <iostream> #include <jsoncpp/json/json.h> int main() { Json::Value root; root["name"] = "Tom"; root["age"] = 18; Json::StreamWriterBuilder builder; builder["indentation"] = " "; // 设置缩进 std::cout << Json::writeString(builder, root) << std::endl; return 0; } ``` 上面的代码生成了一个JSON对象,然后将它转换为JSON字符串并输出。 4. 更多用法 Jsoncpp还提供了很多其他的用法,如数组、嵌套对象、注释等等。如果需要了解更多用法,请参考Jsoncpp的官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值