JsonCpp 使用

JsonCpp 使用

前言

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

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

值类型

value.h头文件中定义的enum ValueType

/** \brief Type of the value held by a Value object.
 */
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).
};
  • 对于浮点数realValue类型,需要注意到由于数据是由二进制构成有的数据并不能精确表示,需要注意精度问题

Value 类中提供了 type() 用于获取值类型(ValueType)

class Value{

    // ...
    ValueType type() const;
    // ...
};

类型判断

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; //是否为数字 实现上等同于isDouble()
    bool isString() const;
    bool isarray() const;
    bool isObject() const;
    // ...
};
  • 对于函数bool isDouble() const;,只要是数字就会返回true,即使这个数字超过64位

类型转换

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

键值判断

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

用法

头文件

#include <jsoncpp/json/json.h>

jsconcpp 安装完毕后,json.h头文件可以在/usr/include/jsoncpp/json/路径找到

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

编译

g++ test.cpp -ljsoncpp

编译时需要链接jsoncpp

读json数据

void testReader() {
    std::string str = "{\"arrayType\":[0,1,2,3],\"objectType\":{\"numberType\":1024,\"stringType\":\"Hello JsonCpp\"}}";

    Json::Value root;
    Json::Reader read;
    if (read.parse(str, root)) {
        // 读取arrayType里的第3个数据
        if (root.isObject() && root.isMember("arrayType") && root["arrayType"].size() >= 3 && root["arrayType"][2].isInt()) {
            std::cout << root["arrayType"][2].asInt() << std::endl;
        }
    }
}

写json数据

void testWriter() {
    Json::Value root;
    for (int i = 0; i <= 3; i++) root["arrayType"].append(i);

    Json::Value obj;
    obj["numberType"] = 1024;
    obj["stringType"] = "Hello JsonCpp";
    root["objectType"] = obj;

    root["objType"]["numberType"] = 2025;
    root["objType"]["stringType"] = "Hello JsonCpp";


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

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

读json数据从文件中

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);
    // ...
};
// test.json 文件内容
{
   "arrayType" : [ 0, 1, 2, 3 ],
   "objectType" : {
      "numberType" : 1024,
      "stringType" : "Hello JsonCpp"
   }
}
// #include <fstream> 需要包含文件流头文件
void testFileReader() {
    const char* path = "test.json";
    std::ifstream ifs(path);
    if (!ifs) {
        std::cerr << "open " << path << " failed\n";
        return;
    }

    Json::Reader read;
    Json::Value root;
    if (read.parse(ifs, root)) {
        if (root.isObject() && root.isMember("objectType") && root["objectType"].isMember("numberType") && root["objectType"]["numberType"].isInt()) {
            std::cout << root["objectType"]["numberType"].asInt() << std::endl;
        }
    }
}

写json数据到文件中

void testFileWeiter() {
    Json::Value root;
    for (int i = 0; i <= 3; i++) root["arrayType"].append(i);

    std::ofstream ofs("test.json");
    if (!ofs) {
        std::cerr << "open test.json failed\n";
        return;
    }
    ofs << root.toStyledString();
    ofs.close();
}
posted @ 2025-04-09 17:59  菜狗非狗  阅读(11)  评论(0)    收藏  举报