首页 > 其他分享 >jsoncpp按写入顺序读取

jsoncpp按写入顺序读取

时间:2024-05-17 23:29:48浏览次数:18  
标签:JsonValue const 读取 写入 jsoncpp Json Value key operator

jsoncpp按写入顺序读取

在不修改jsoncpp源码的基础上,按照写入顺序读取,编写JsonValue类派生自Json::Value。

jsonvalue.h

#ifndef JSONVALUE_H
#define JSONVALUE_H

#include <jsoncpp/json/json.h>

class JsonValue : public Json::Value
{
public:
    static inline Json::Value &toValue(JsonValue &value)
    {
        return *reinterpret_cast<Json::Value*>(&value);
    }
    static inline JsonValue &fromValue(Json::Value &value)
    {
        return *reinterpret_cast<JsonValue*>(&value);
    }
    static inline const Json::Value &toConstValue(const JsonValue &value)
    {
        return *reinterpret_cast<const Json::Value*>(&value);
    }
    static inline const JsonValue &fromConstValue(const Json::Value &value)
    {
        return *reinterpret_cast<const JsonValue*>(&value);
    }
public:
    JsonValue(Json::ValueType type = Json::ValueType::nullValue):Json::Value(type){}
    JsonValue(Int value):Json::Value(value){}
    JsonValue(UInt value):Json::Value(value){}
#if defined(JSON_HAS_INT64)
    JsonValue(Int64 value):Json::Value(value){}
    JsonValue(UInt64 value):Json::Value(value){}
#endif // if defined(JSON_HAS_INT64)
    JsonValue(double value):Json::Value(value){}
    JsonValue(const char* value):Json::Value(value){}
    JsonValue(const char* begin, const char* end):Json::Value(begin, end){}
    JsonValue(const Json::StaticString& value):Json::Value(value){}
    JsonValue(const JSONCPP_STRING& value):Json::Value(value){}///< Copy data() til size(). Embedded zeroes too.
#ifdef JSON_USE_CPPTL
    JsonValue(const CppTL::ConstString& value):Json::Value(value){}
#endif
    JsonValue(bool value):Json::Value(value){}
    JsonValue(const Json::Value& other):Json::Value(other){}
    JsonValue(const JsonValue& other):Json::Value(toConstValue(other)){}
#if JSON_HAS_RVALUE_REFERENCES
    JsonValue(JsonValue&& other):Json::Value(other){}
#endif
    JsonValue& operator=(JsonValue other) {return fromValue(Json::Value::operator=(toValue(other)));}
    void swap(Value& other){Json::Value::swap(other);}
    void swapPayload(Value& other){Json::Value::swapPayload(other);}
    Json::ValueType type() const{return Json::Value::type();}
    /// Compare payload only, not comments etc.
    bool operator<(const JsonValue& other) const{return Json::Value::operator<(other);}
    bool operator<=(const JsonValue& other) const{return Json::Value::operator<=(other);}
    bool operator>=(const JsonValue& other) const{return Json::Value::operator>=(other);}
    bool operator>(const JsonValue& other) const{return Json::Value::operator>(other);}
    bool operator==(const JsonValue& other) const{return Json::Value::operator==(other);}
    bool operator!=(const JsonValue& other) const{return Json::Value::operator!=(other);}
    int compare(const JsonValue& other) const{return Json::Value::compare(other);}
public:
    JsonValue& operator[](ArrayIndex index){return fromValue(Json::Value::operator[](index));}
    JsonValue& operator[](int index){return fromValue(Json::Value::operator[](index));}
    const JsonValue& operator[](ArrayIndex index) const{return fromConstValue(Json::Value::operator[](index));}
    const JsonValue& operator[](int index) const {return fromConstValue(Json::Value::operator[](index));}
    JsonValue get(ArrayIndex index, const JsonValue& defaultValue) const{return Json::Value::get(index, defaultValue);}
    JsonValue& append(const JsonValue& value){return fromValue(Json::Value::append(value));}
    const JsonValue& operator[](const char* key) const{return fromConstValue(Json::Value::operator[](key));}
    const JsonValue& operator[](const JSONCPP_STRING& key) const{return fromConstValue(Json::Value::operator[](key));}
    JsonValue get(const char* key, const JsonValue& defaultValue) const{return Json::Value::get(key, defaultValue);}
    JsonValue get(const char* begin, const char* end, const JsonValue& defaultValue) const{return Json::Value::get(begin, end, defaultValue);}
    JsonValue get(const JSONCPP_STRING& key, const JsonValue& defaultValue) const{return Json::Value::get(key, defaultValue);}
#ifdef JSON_USE_CPPTL
    JsonValue get(const CppTL::ConstString& key, const JsonValue& defaultValue) const{return Json::Value::get(key, defaultValue);}
#endif
    JsonValue const* find(char const* begin, char const* end) const {return reinterpret_cast<JsonValue const*>(Json::Value::find(begin, end));}
    JsonValue const* demand(char const* begin, char const* end){return reinterpret_cast<JsonValue const*>(Json::Value::demand(begin, end));}
    inline JsonValue& operator[](const JSONCPP_STRING& key){return JsonValue::operator[](key.c_str());}
    inline JsonValue& operator[](const Json::StaticString& key) {return JsonValue::operator[](key.c_str());}
#ifdef JSON_USE_CPPTL
  JsonValue& operator[](const CppTL::ConstString& key){return fromValue(Json::Value::operator[](key));};
  const JsonValue& operator[](const CppTL::ConstString& key) const{return fromValue(Json::Value::operator[](key));};
#endif
    JsonValue removeMember(const JSONCPP_STRING& key){return removeMember(key.c_str());}
    bool removeMember(JSONCPP_STRING const& key, JsonValue* removed){return removeMember(key.c_str(), removed);}
    bool removeMember(const char* begin, const char* end, JsonValue* removed) {return Json::Value::removeMember(std::string(begin, end - begin).c_str(), removed);}
    bool removeIndex(ArrayIndex i, JsonValue* removed) {return Json::Value::removeIndex(i, reinterpret_cast<Json::Value*>(removed));}
public:
    JsonValue& operator[](const char* key);
    Members getMemberNames() const;
    JsonValue removeMember(const char* key);
    bool removeMember(const char* key, JsonValue* removed);
public:
    static    std::string m_KeyWordQueueName;
};

#endif // JSONVALUE_H

jsonvalue.cpp

#include "jsonvalue.h"
std::string JsonValue::m_KeyWordQueueName = "#JsonValue#Members";

JsonValue& JsonValue::operator[](const char* key) {
    if(m_KeyWordQueueName != key)
    {
        if(isMember(m_KeyWordQueueName)) {
            Json::Value& object = Json::Value::operator[](m_KeyWordQueueName.c_str());
            if(object.isArray()) {
                int32_t bufPos = object.size();
                for(int32_t i = 0; i < bufPos; ++i) {
                    if(object[i] == key) {
                        return fromValue(Json::Value::operator[](key));
                    }
                }
                object[bufPos] = key;
            }
            else {
                if(!object.isArray()) Json::Value::operator[](0) = key;
            }
        } else {
            Json::Value::operator[](m_KeyWordQueueName)[0] = key;
        }
    }
    return fromValue(Json::Value::operator[](key));
}

JsonValue::Members JsonValue::getMemberNames() const
{
    JsonValue::Members cache;
    if(isMember(m_KeyWordQueueName)) {
        for(int i = 0; i < static_cast<int>(operator[](m_KeyWordQueueName).size()); ++i) {
            cache.push_back(operator[](m_KeyWordQueueName)[i].asString());
        }
    }
    return cache;
}

JsonValue JsonValue::removeMember(const char* key)
{
    if(m_KeyWordQueueName != key) {
        JsonValue::Members cache;
        bool flag = false;
        if(isMember(m_KeyWordQueueName)) {
            for(int i = 0; i < static_cast<int>(operator[](m_KeyWordQueueName).size()); ++i) {
                const auto &name = operator[](m_KeyWordQueueName)[i].asString();
                if(name == key) {
                    flag = true;
                } else {
                    cache.push_back(name);
                }
            }
        }
        if(flag) {
            Json::Value::removeMember(m_KeyWordQueueName, this);
            for(int i = 0; i < static_cast<int>(cache.size()); ++i) {
                Json::Value::operator[](m_KeyWordQueueName)[i] = cache[i];
            }
        }
    }
    return JsonValue(Json::Value::removeMember(key));
}

bool JsonValue::removeMember(const char* key, JsonValue* removed)
{
    if(m_KeyWordQueueName != key) {
        JsonValue::Members cache;
        bool flag = false;
        if(isMember(m_KeyWordQueueName)) {
            for(int i = 0; i < static_cast<int>(operator[](m_KeyWordQueueName).size()); ++i) {
                const auto &name = operator[](m_KeyWordQueueName)[i].asString();
                if(name == key) {
                    flag = true;
                } else {
                    cache.push_back(name);
                }
            }
        }
        if(flag) {
            Json::Value::removeMember(m_KeyWordQueueName, this);
            for(int i = 0; i < static_cast<int>(cache.size()); ++i) {
                Json::Value::operator[](m_KeyWordQueueName)[i] = cache[i];
            }
        }
    }
    return Json::Value::removeMember(key, reinterpret_cast<Json::Value*>(removed));
}

main.cpp

#include <QCoreApplication>
#include <QDebug>
#include "jsonvalue.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    JsonValue root;
    constexpr bool shouldUseOldWay = false;
    int count = 0;
    root["className"] = "高一(3)班";
    root["teacher"]["name"] = "小王";
    root["teacher"]["age"] = 28;

    //数组
    root["student"][count]["name"] = "张三";
    root["student"][count]["age"] = 15;
    root["student"][count]["friend"]["name"] = "大黄";
    root["student"][count]["friend"]["age"] = 3;
    ++count;
    root["student"][count]["name"] = "李四";
    root["student"][count]["age"] = 14;
    root["student"][count]["friend"]["name"] = "小黑";
    root["student"][count]["friend"]["age"] = 3;
    ++count;
    root["student"][count]["name"] = "王五";
    root["student"][count]["age"] = 13;
    root["student"][count]["friend"]["name"] = "大花";
    root["student"][count]["friend"]["age"] = 3;
    ++count;


    if (shouldUseOldWay) {
        Json::FastWriter writer;
        const std::string json_file = writer.write(root);
        qInfo() << json_file.c_str();
    } else {
        Json::StreamWriterBuilder builder;
        const std::string json_file = Json::writeString(builder, root);
        qInfo() << json_file.c_str();
    }

    return a.exec();
}

以派生类JsonValue代替基类Json::Value即可自动实现key值顺序记录,读取时使用getMemberNames获取到的key值数组中的key值顺序与写入时相同。

标签:JsonValue,const,读取,写入,jsoncpp,Json,Value,key,operator
From: https://www.cnblogs.com/yuanhaoblog/p/18198897

相关文章

  • python常见图片格式-读取方法-相互转换
    PIL读取image=Image.open({path})格式h,wTensor读取image=Image.open(image_name).convert('RGB')image=transforms.ToTensor()(image)格式:3,height,width数据类型:float32----tensor颜色通道顺序:RGBOpencv读取cv2.imread({path})格式:heightwi......
  • C++读取配置文件
    1、读取=号的配置文件(或者:)的配置。#include<iostream>#include<fstream>#include<sstream>#include<map>#include<string>std::map<std::string,std::string>read_config(conststd::string&filename){std::map<std::st......
  • qt的xml读取和使用
    将数据保存文件QByteArrayfileAsByteArray;QFilefile(filename);if(!file.open(QIODevice::WriteOnly)){qDebug()<<"文件未打开.";}file.write(fileAsByteArray);file.close();读取文件QByteArraybyteArray=file.readAll();使用xml分析文件QXmlStre......
  • selenium4中cookie的保存与读取
    selenium4中网页cookie的保存与读取importjsonfromseleniumimportwebdriverdriver=webdriver.Edge()url='https://baidu.com'driver.get(url)保存当前网页的cookiedefsavecks():cookies=driver.get_cookies()jscookies=json.dumps(cookies)......
  • rust项目中通过log4rs将日志写入文件
    java项目中使用最广泛的日志系统应该是log4j(2)了。如果你也是一个Java程序员,可能在写rust的时候会想怎么能顺手地平移日志编写习惯到rust中来。log4rs就是干这个的。从名字就能看出来。将Java编程习惯代人rust不是一种好的方向,毕竟两种语言定位不同。不过单纯练手就无所谓了......
  • hive写入star,csv格式的streamload-简单版
    hive写入star,csv格式的streamload注意字符串中的转移字符直接拼接\n而要显示\\是非转义字符publicclassGcyDataTrans{privatestaticStringSTARROCKS_HOST="IP";privatestaticStringSTARROCKS_HTTP_PORT="8030";privatestaticStringSTARROCKS_DB......
  • 利用python脚本批量读取当前目录下所有excle表格中特定的单元格内容
    利用python脚本批量读取当前目录下所有excle表格中特定的单元格内容importosfromopenpyxlimportload_workbook#设置要读取的单元格地址cell_address='N18'#遍历当前目录下的所有文件forfilenameinos.listdir('.'):iffilename.endswith(......
  • 使用 PHP 创建 Excel 读取器类
    介绍:PHPExcel-1.8.1读取excel创建ExcelReader类:ExcelReader类旨在从Excel文件中读取数据。它以文件路径作为输入,并提供一个方法来从Excel文件中读取数据。<?phprequire_once"lib/PHPExcel-1.8.1/Classes/PHPExcel.php";classExcelReader{protected$file;......
  • stm32f103c8t6对flash进行操作,Hal库,擦除1页数据大小,写入128字节大小,读取指定地址128字
    参考这篇:STM32IAP应用开发——自制BootLoader-CSDN博客把工程转到HAL库使用的函数,用HAL自带的HAL_FLASHEx_EraseHAL_FLASH_Program 串口显示结果 验证没问题flash在hal库使用的驱动程序#include"flash.h"externvoidFLASH_PageErase(uint32_tPageAddress);//......
  • Adobe ColdFusion 任意文件读取漏洞
    漏洞描述由于AdobeColdFusion的访问控制不当,未经身份认证的远程攻击者可以构造恶意请求读取目标服务器上的任意文件,泄露敏感信息。Fofa:app="Adobe-ColdFusion"&&title=="ErrorOccurredWhileProcessingRequest"POC通过特定的ColdFusion管理端点获取UUIDGET/CFIDE/ad......