文章目录
安装
命令行安装
sudo apt-get update
sudo apt-get install libjsoncpp-dev
源代码安装(道理和安装其他包一样)
- 在github下载源代码
- 解压源代码
tar zxvf ./jsoncpp-1.9.5.tar.gz
- 建立build文件夹编译安装
cd json
mkdir build
cd build
cmake ..
make
sudo make install
- 最后更新系统库链接
ldconfig
介绍
Jsoncpp库中的类被定义到了一个Json命名空间中,建议在使用这个库的时候先声明这个明明空间;
using namespace Json;
使用**Jsoncpp**
库解析**json**
格式的数据,我们只需要掌握三个类:
- Value类:将json支持的数据类型进行了包装,最终得到一个Value类型。
- FastWriter类:将Value对象中的数据序列化为字符串。
- 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序列化数据到磁盘
首先介绍文件组织结构:
- 编写src/CMakeLists.txt文件:
add_executable(json_str main.cpp)
target_link_libraries(json_str jsoncpp)
- 编写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)
- 编写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;
}
- 测试结果(成功保存)
解析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;
}
运行结果: