Jsoncpp的使用

 


动态库和静态库

生成

https://github.com/open-source-parsers/jsoncpp

下载后通过cmake生成vs项目

生成后得到vs项目

打开sln文件之后,右键jsoncpp lib,生成lib和dll文件

lib在/lib/Debug下,dll在/bin/Debug下
这里的lib相当于一个.h,dll是.cpp,因此配合使用,

Jsoncpp的使用

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

using namespace Json;

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

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

value类

枚举类型 说明 翻译
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串中的{}

构造函数

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

VS的配置


简单的示例代码

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

using namespace std;
using namespace Json;
/*示例数据
[
    12, 
    true, 
    "tom", 
    ["jack", "ace", "robin"], 
    {"sex":"man", "girlfriend":"lucy"}
]
*/

void writeJson()
{
	Value root;
    root.append(12);
    root.append(true);
    root.append("tom");
    //创建一个子数组
    Value subArray1;
    subArray1.append("jack");
    subArray1.append("ace");
    subArray1.append("robin");
    root.append(subArray1);
    //创建一个子对象
    Value subObj;
    subObj["sex"] = "man";
    subObj["girlfriend"] = "lucy";
    root.append(subObj);

#if 1
    string json = root.toStyledString();
#else
    FastWriter w;
    string json = w.write(root);
#endif
    //写入文件
    ofstream ofs("test.json");
    ofs << json;
    ofs.close();

}

void readJson()
{
    //打开文件
    ifstream ifs("test.json");
    Reader r;
    Value root;
    //用reader解析并导入root中
    r.parse(ifs, root, true);
    if (root.isArray())
    {
        for (int i = 0; i < root.size(); i++)
        {
            Value item = root[i];
            //如果是int类型,就变成it输出
            if (item.isInt())
            {
                cout << item.asInt() << endl;
            }
            else if (item.isString())
            {
                cout << item.asString() << endl;
            }
            else if (item.isBool())
            {
                cout << item.asBool() << endl;
            }
            else if (item.isArray())
            {
                for (int j = 0; j < item.size(); j++)
                {
                    cout << item[j].asString() << endl;
                }
            }
            else if (item.isObject())
            {
                Value::Members keys = item.getMemberNames();
                for (int j = 0; j < keys.size(); j++)
                {
                    cout << keys.at(j) << " : " << item[keys[j]] << endl;
                }
            }
        }
    }
}

int main()
{
    writeJson();
    readJson();
    return 0;
}
posted @   LiviaYu  阅读(273)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示