菜鸟笔记
提升您的技术认知

JsonCpp 使用指导

前言

JSON 是一种轻量级数据交换格式。它可以表示数据、字符串、有序的值序列以及名称/值对的集合。

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

JsonCpp 目前在 github 上托管。

官方网址:https://github.com/open-source-parsers/jsoncpp

安装 JsonCpp 开发包

在 ubuntu 系统既可以通过命令行安装也可以使用界面进行安装。

  • 命令行安装:
sudo apt install -y libjsoncpp-dev
  • 使用软件包管理器进行安装,启动 Synaptic 软件,搜索 jsoncpp 关键字,在过滤出来的条目中点击 libjsoncpp-dev 然后选择 “Mark for Installation”:

扩展阅读:Synaptic 软件的介绍及安装使用教程可参考: Ubuntu 软件包管理利器 - 新立得 (Synaptic)

嵌入式开发

如果需要在嵌入式系统使用 JsonCpp 可以参考《交叉编译 JsonCpp 库》一文,利用交叉编译器编译出 JsonCpp 头文件及静态/动态库文件。

用法

头文件

#include <json/json.h>

头文件中包含了 Reader, Writer, Value 这三个重要的类。

读取 json 数据

按照国际惯例,每一项技术的学习都可以从 “Hello World” 开始,以下面的 json 字符串为例:

{
  "content": "Hello JsonCpp"}

使用 ReaderValue 读取 content 的值:

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

int main(int argc, char const *argv[])
{
  
    std::string str = "{\"content\": \"Hello JsonCpp\"}";

    Json::Reader reader;
    Json::Value root;
    if (reader.parse(str, root))
        std::cout << root["content"].asString() << std::endl;
    
    return 0;
}

在 ubuntu 系统上编译:

g++ -I/usr/include/jsoncpp -o hello hello.cpp -ljsoncpp

运行结果:

$ ./hello
Hello JsonCpp

在源码第 9~10 行,定义了两个对象 readerroot:

Json::Reader reader;
Json::Value root;

在源码第 11~12 行,调用 Reader.parse() 接口尝试解析 json 字符串 str,当 str 满足 json 格式之后,调用 Value[] 操作符将 “content” 的值取出来,然后再进行类型转换,取出实际的类型数据:

if (reader.parse(str, root))
    std::cout << root["content"].asString() << std::endl;

关于类型数据的转换在接下来的章节进行详细说明。

值类型

JsonCpp 支持的值类型总共有 8 种:

enum ValueType Description
0 nullValue ‘null’ value
1 intValue signed integer value
2 unsigned int unsigned integer value
3 realValue double value
4 stringValue UTF-8 string value
5 booleanValue bool value
6 arrayValue array value (ordered list)
7 objectValue object value (collection of name/value pairs)

可以参考 json/value.h 头文件中定义的 enum ValueType。在 Value 类中提供了 type() 用于获取值类型(ValueType),type() 定义如下:

class Value {
  
    ...
    ValueType type() const;
    ...
};

类型判断

如果需要进行类型判断,Json::Value 已经提供了完备的类型判断接口供调用:

class Value {
  
    ...
    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;
    ...
};

其中这里有两个接口比较特殊,一个是 isNumeric() 另一个是 isIntegral()

先对 isNumeric() 进行说明,字面意思就是“是否为数字”,实际上在 Json::Value 类的实现中等同于 isDouble(),因此这两个函数是等效的,实现代码如下:

bool Value::isNumeric() const {
   return isDouble(); }

在使用过程中可以直接用 isDouble() 代替 isNumeric(),反之亦然。

isIntegral() 的作用主要是对浮点型数据的值进行了严格限制,如果类型为 int 或者 uint,该接口直接返回真值。如果类型为 double,因为 maxUInt64( = 2 64 − 1 =2^{64}-1 =264−1)不能精确表示为 double,因此 double(maxUInt64)将四舍五入为 2 64 2^{64} 264。因此,我们要求该值严格小于限制。

类型转换

当需要进行类型转换时,Json::Value 已经提供了常用的类型转换接口供调用:

class Value {
  
    ...
    const char *asCString() const;
    String asString() const;
    Int asInt() const;
    Int64 asInt64() const;
    UInt asUInt() const;
    UInt64 asUInt64() const;
    float asFloat() const;
    double asDouble() const;
    bool asBool() const;
    ...
};
Type Interface Content
const char * asCString() 转换成 C 字符串 const char *
String asString() 转换成 C++ 字符串 std::string
Int asInt() 转换成 int 型
Int64 asInt64() 转换成 64 位 int 型
UInt asUInt() 转换成 unsigned int 型
UInt64 asUInt64() 转换成 64 位 unsigned int 型
float asFloat() 转换成 float 型
double asDouble() 转换成 double 型
bool asBool() 转换成 bool 型

键值判断

Value.isMember() 接口用于判断 json 字符串中是否存在某个键值,函数原型:

class Value {
  
    ...
    /// Return true if the object has a member named key.
    /// \note 'key' must be null-terminated.
    bool isMember(const char* key) const;
    /// Return true if the object has a member named key.
    /// \param key may contain embedded nulls.
    bool isMember(const String& key) const;
    /// Same as isMember(String const& key)const
    bool isMember(const char* begin, const char* end) const;
    ...  
};

判断 “content” 是否为 json 的键:

root.isMember("content");

结合类型判断接口,如果需要确定 json 中是否存在 “content” 键值,并且 “content” 的值为 string 类型,可以加入这样的判断条件:

if (root.isMember("content") && root["content"].isString()) {
  
    // do something...
    val = root["content"].asString();
}

遍历 json 数据

Value::Members 对象存储了 json 的 key 列表,原型是一个字符串的矢量数组:

class Value {
  
    ...
    using Members = std::vector<String>; 
    ...
};

可以通过 Value.getMemberNames() 接口获取,示例代码如下:

Json::Value root;
if (reader.parse(str, root)) {
  
    Json::Value::Members mem = root.getMemberNames();
    for (auto key : mem) 
        std::cout << key << std::endl;
}

如果需要将 json 的内容全部遍历出来,可以使用递归的方式来达成。

  1. 从最外层开始进入
  2. 如果是 Object 类型,利用 getMemberNames() 接口遍历所有的 key
  3. 如果在遍历过程中遇到 Object/Array 类型,则递归从步骤 1 开始
  4. 如果是普通类型,直接打印

示例代码如下,其中 print_json() 递归执行:

void show_value(const Json::Value &v) {
  
    if (v.isBool()) {
  
        std::cout << v.asBool() << std::endl;
    } else if (v.isInt()) {
  
        std::cout << v.asInt() << std::endl;
    } else if (v.isInt64()) {
  
        std::cout << v.asInt64() << std::endl;
    } else if (v.isUInt()) {
  
        std::cout << v.asUInt() << std::endl;
    } else if (v.isUInt64()) {
  
        std::cout << v.asUInt64() << std::endl;
    } else if (v.isDouble()) {
  
        std::cout << v.asDouble() << std::endl;
    } else if (v.isString()) {
  
        std::cout << v.asString() << std::endl;
    }
}

void print_json(const Json::Value &v) {
  
    if (v.isObject() || v.isNull()) {
  
        Json::Value::Members mem = v.getMemberNames();
        for (auto key : mem) {
  
            std::cout << key << "\t: ";
            if (v[key].isObject()) {
  
                std::cout << std::endl;
                print_json(v[key]);
            } else if (v[key].isArray()) {
  
                std::cout << std::endl;
                for (auto i = 0; i < v[key].size(); i++)
                    print_json(v[key][i]);
            } else
                show_value(v[key]);
        }
    } else
        show_value(v);
}

体现在用法上就是直接将 Json::Value 作为参数代入函数接口:

Json::Value root;
if (reader.parse(str, root))
    print_json(root);

读取数组

JsonCpp 提供了多种方式来读取数组,可以利用下标进行读取,可以使用 iterator 进行读取,也可以直接使用 C++11 特性进行读取。下面是一个简单例子:

{
   "list": [1, 2, 3] }

使用下标方式进行读取:

for (int i = 0; i < root["list"].size(); ++i)
    std::cout << root["list"][i].asInt();

使用 Json::ValueIterator 或者 Json::ValueConstIterator 进行读取:

Json::ValueIterator it = root["list"].begin();
for (; it != root["list"].end(); ++it)
    std::cout << it->asInt();

使用 C++11 特性(最简单):

for (auto it : root["list"])
    std::cout << it.asInt();

如果数组是 ObjectValue 类型,比如说类似这种:

{
  
    "list": [
        {
  
            "name": "John",
            "sex": "man"
        },
        {
  
            "name": "Marry",
            "sex": "women"
        }
    ]
}

则数组的读取代码类似于:

for (auto it : root["list"]) {
  
    std::cout << it["name"].asString() << std::endl;
    std::cout << it["sex"].asString() << std::endl;
}

写 json 数据

JsonCpp 提供 Writer 类用于写 json 数据。还是从最简单的例子开始,然后逐步展开。比如利用 JsonCpp 创建如下 json 文件:

{
  "content": "Hello JsonCpp"}

使用 Value 创建 json 字符串然后转换成 std::string 类型并输出:

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

int main(int argc, char const *argv[])
{
  
    Json::Value root;
    root["content"] = "Hello JsonCpp";
    std::cout << root.toStyledString();
    return 0;
}

在 ubuntu 系统上编译:

g++ -I/usr/include/jsoncpp -o hello hello.cpp -ljsoncpp

运行结果:

$ ./hello
{
  
   "content" : "Hello JsonCpp"
}

源码第 6 行定义出 Value 对象,作为 json 的根节点(root node):

Json::Value root;

源码第 7 行定义 Key/Value 键值对,以此类推,在节点下的基本类型均可使用 [] 操作符进行添加,如:

root["string_key"] = "string value";
root["int_key"] = 256;
root["double_key"] = 128.6;
root["boolean_key"] = true;

源码第 8 行利用 Value 提供的转换接口可将 json 进行格式化,函数原型为:

class Value {
  
    ...
    String toStyledString() const;
    ...
};

添加 ObjectValue 类型

如果需要添加嵌套的 json 子节点,可以定义一个 Value 对象来装载内部的 Key/Value 键值对,然后将该对象赋值给 json 的父节点:

Json::Value sub;
sub["province"] = "Guangdong";
sub["city"] = "Huizhou";

root["hometown"] = sub;
sub.clear();

如果嵌套的节点内容较简单,不想重新定义一个新的 Value 变量也可以采用另一种写法:

root["hometown"]["province"] = "Guangdong";
root["hometown"]["city"] = "Huizhou";

以上两种写法最终产生的 json 内容都是一样的,如下所示:

{
  
    "hometown": {
  
        "province": "Guangdong",
        "city": "Huizhou"
    }
}

添加数组类型

Value.append() 接口用于添加 json 数组类型,凡事宜从最简单的地方入手,一步一步深入:

for (int i = 0; i < 3; ++i)
    root["list"].append(i);

生成的 json 内容如下:

{
  
    "list": [0, 1, 2]
}

如果数组内的数据是 ObjectValue 类型,可以定义一个 Value 对象来装载内部的 Key/Value 键值对,然后将该对象添加到数组中:

Json::Value item;
for (int i = 0; i < 2; ++i) {
  
    item["index"] = i;
    item["content"] = "Hello Array";
    root["data"].append(item);
}

生成的 json 内容如下:

{
  
   "data" : [
      {
  
         "content" : "Hello Array",
         "index" : 0
      },
      {
  
         "content" : "Hello Array",
         "index" : 1
      }
   ]
}

格式化与非格式化

根据使用场合不同,需要将 json 内容转换为格式化或非格式化字符串,比如为了可视化的输出一般选择格式化 json 字符串,而在网络传输过程中,会尽量选择使用非格式化的字符串来达到减少传输数据量的目的。

    Json::Value root;
    ...// root 中写入数据

    // 格式化: 转为格式化字符串,里面加了很多空格及换行符
    std::string strJson = root.toStyledString();

    // 非格式化: 转为未格式化字符串,无多余空格及换行符
    Json::FastWriter writer;
    std::string strJson = writer.write(root);

写入文件

在这一小节的介绍中,更多的是说明标准 C++ 的文件流操作,因为上文已经通过格式化与非格式化将 json 字符串导出成一个标准 C++ 的字符串 std::string,接下来直接将 std::string 写入到文件中即可。示例代码:

    // root node
    Json::Value root;
    ...

    try {
  
        std::ofstream ofs;
        ofs.open(filename);
        if (ofs.fail()) {
  
            fprintf(stderr, "open '%s' failed: %s", filename, strerror(errno));
            return false;
        }
        ofs << root.toStyledString();
        ofs.close();
    } catch (std::exception &e) {
  
        fprintf(stderr, "%s", e.what());
        return false;
    }

源码第 6 行定义输出文件流对象 ofs:

std::ofstream ofs;

源码第 7~11 行尝试打开文件,如果文件无法打开,使用 strerror(errno) 查看具体失败原因。

ofs.open(filename);
if (ofs.fail()) {
  
    ...
}

源码 12 行将 json 内容通过流方式写入文件中。

ofs << root.toStyledString();

在文件写入完成之后使用 ofs.close() 接口关闭文件流。因为写入的过程在实际的系统运行会出现较复杂的情况:磁盘満了又或者磁盘损坏导致无法写入等,所以如果在写入的过程中出现异常,我们就需要使用 try...catch... 来捕获异常。

从文件读取

Reader 支持从 std::istream 流读取数据,可以直接将文件流作为输入参数给到 Reader.parse(),函数原型为:

class Reader {
  
    ...
    bool parse(const std::string& document, Value& root, bool collectComments = true);
    bool parse(IStream& is, Value& root, bool collectComments = true);
    ...
};

比如现在有一个文件 hello.json

{
  
    "content": "Hello JsonCpp"
}

代码实现:

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

int main(int argc, char const *argv[])
{
  
    const char *path ="hello.json"; 
    std::ifstream ifs(path);
    if (!ifs) {
  
        printf("open '%s' failed: %s\n", path, strerror(errno));
        return 1;
    }

    Json::Reader reader;
    Json::Value root;
    if (reader.parse(ifs, root)) {
  
        if (root.isMember("content") && root["content"].isString()) {
  
            printf("%s\n", root["content"].asCString());
        }
    }
    
    return 0;
}

源码中第 10 行使用 std::ifstream 读取 json 文件,如果文件无法打开,使用 strerror(errno) 查看具体失败原因。

std::ifstream ifs(path);
if (!ifs) {
  
    ...
}

源码第 18 行将 ifs 作为参数传入 parse() 接口:

if (reader.parse(ifs, root)) {
  
    ...
}

设计经验

从面向对象的设计思想出发,建议将每份 json 的读写设计成一个独立的类,这里面所指的“每份 json”可以是 json 字符串或者是 json 文件,以这样的方式来进行设计之后,业务层只需要关心期望取得的键值即可。