jsoncpp的基本操作

基本概念:

 

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

 

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

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


2.1 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;
2.2 FastWriter 类

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


2.3 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);

 3. json 读写

为什么要用json文件呢?

我们最常使用的存储数据的方式有很多,比如利用txt文件存,利用xml存,利用word存,利用Excel存,如果我们要求比较高,还可以使用数据库存。

相对于txt,word来说,json格式更加明确,获取重要信息非常方便。

相对于xml来说,json格式更加简洁,存储同样的文件,花费的内存更小。

相对于Excel来说,json更适合存储字符类文件。Excel相当于比较简单的数据库了。

相对于数据库来说,json更加方便,数据库我们还需要做一些设置,安装一些软件。json可以直接使用。

JSON 比更小、更快,更易解析。JSON 易于人阅读和编写。C、Python、C++、Java、PHP、Go等编程语言都支持 JSON。

二、JSON的实例如下:

{
"sites": [
{ "name":"百度" , "url":"www.baidu.com" },
{ "name":"google" , "url":"www.google.com" },
{ "name":"微博" , "url":"www.weibo.com" }
]
}

 

JSON语法:

数据在 名称/值 对中
数据由逗号 , 分隔
使用斜杆来转义 \ 字符
大括号 {} 保存对象

三、C++操作json文件
读取JSON文件之前,首先要了解jsoncpp库中的两个类:Value和Reader。
在这里我就不多讲了,可以参考这篇博客:
Value、Reader

json数据如下

{
"name" : "shuiyixin",
"age" : "21",
"sex" : "man"
}


读取代码如下:

void readStrJson()
{
//字符串
string str =
"{\"name\":\"shuiyixin\",\"age\":21,\"sex\":\"man\"}";
//声明类的对象
Json::Reader reader;
Json::Value root;

//从字符串中读取数据
if (reader.parse(str, root))
{
string name = root["name"].asString();
int age = root["age"].asInt();
string sex = root["sex"].asString();
//输出
cout << name+ "," << age << "," << sex << endl;
}

}

读取JSON文件

{
"A": {
"type": "SINT",
"value": 0
},
"age": "18",
"B": {
"type": "INT",
"value": 0
},
"C": {
"type": "DATE",
"value": {
"year": [ "2019", "2013", "2012" ],
"month": [ "1", "2", "3" ]

}
},
"friend": {
"friend_age": "18",
"friend_name": "qiwen",
"friend_sex": "man"
},
"hobby": [ "bamintan", "eat", "rap" ],
"name": "hemenglin",
"sex": "male"

}

 

读取文件相关的代码如下:

void readFileJson()
{
Json::Reader reader;
Json::Value root;

ifstream in("demo.json", ios::binary);
if (!in.is_open())
{
cout << "Error opening file\n";
return ;
}
if (reader.parse(in, root))
{
string name = root["name"].asString();
string age = root["age"].asString();
string sex = root["sex"].asString();

cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "sex:" << sex << endl;


string friend_name = root["friend"]["friend_name"].asString();
string friend_age = root["friend"]["friend_age"].asString();
string friend_sex = root["friend"]["friend_sex"].asString();

string atype = root["A"]["type"].asString();
string avalue = root["A"]["value"].asString();

string btype = root["B"]["type"].asString();
string bvalue = root["B"]["value"].asString();

cout << "atype:" << atype << endl;
cout << "avalue:" << avalue << endl;

cout << "btype:" << btype << endl;
cout << "bvalue:" << bvalue << endl;

cout << "friend_name:" << friend_name << endl;
cout << "friend_age:" << friend_age << endl;
cout << "friend_sex:" << friend_sex << endl;

cout << "hobby:" << endl;
for (unsigned int i = 0; i < root["hobby"].size(); i++)
{
string str = root["hobby"][i].asString();
cout << str << "\t";
}

string Ctype = root["C"]["type"].asString();
cout << "Ctype:" << Ctype << endl;
//string Cvalue = root["C"]["value"]["year"].asString();
//cout << "Cvalue:" << Cvalue << endl;

cout << "DATE OF YEAR:" << endl;
for (unsigned int i = 0; i < root["C"]["value"]["year"].size(); i++)
{
string str = root["C"]["value"]["year"][i].asString();
cout << str << "\t";
}




}
else
{
cout << "parse error\n" << endl;
}
in.close();

}

 


读的效果如图:


写入JSON文件
写入的文件就是上面的demo.json文件,代码如下:

void writeFileJson()
{
//根节点
Json::Value root;
root["name"] = Json::Value("hemenglin");
root["age"] = Json::Value("18");
root["sex"] = Json::Value("male");

//子节点
Json::Value bro;
bro["friend_name"] = Json::Value("qiwen");
bro["friend_age"] = Json::Value("18");
bro["friend_sex"] = Json::Value("man");

root["friend"] = Json::Value(bro);


//ctest
Json::Value Ctest;
Ctest["type"] = Json::Value("DATE");
Ctest["value"] = Json::Value();
root["C"] = Json::Value(Ctest);

Json::Value Ctest2;
Ctest2["year"] = Json::Value();
Ctest2["month"] = Json::Value();
Ctest2["day"] = Json::Value();
root["C"]["value"] = Json::Value(Ctest2);



root["C"]["value"]["year"].append("2019");
root["C"]["value"]["year"].append("2013");
root["C"]["value"]["year"].append("2012");

root["C"]["value"]["month"].append("3");
root["C"]["value"]["month"].append("2");
root["C"]["value"]["month"].append("1");
//ctest

//数组形式
root["hobby"].append("bamintan");
root["hobby"].append("eat");
root["hobby"].append("rap");


cout << "\nStyledWriter:" << endl;
Json::StyledWriter sw;
cout << sw.write(root) << endl << endl;

ofstream os;
os.open("demo.json", std::ios::out);
if (!os.is_open())
{
cout << "error:can't find the file" << endl;
}
os << sw.write(root);
os.close();

}

写的效果如图:

 可以参考:

https://blog.csdn.net/hml111666/article/details/127227992

https://subingwen.cn/cpp/jsoncpp/?highlight=json

posted @ 2024-04-15 11:04  白伟碧一些小心得  阅读(1060)  评论(0编辑  收藏  举报