解析和显示 CBOR 数据

演示如何解析 CBOR 格式的文件。

本例演示了如何直接使用QCborStreamReader 类解析 CBOR 内容。cbordump 程序从文件或标准输入端读取 CBOR 格式的内容,并以人类可读的格式将解码后的内容转储到 stdout。它可以以 CBOR 诊断符号(类似于 JSON)输出,也可以产生详细输出,在详细输出中,输入的每个字节都会在旁边显示其编码。

CborDumper 类

CborDumper 类包含一个QCborStreamReader 对象,该对象使用传递给 CborDumper 构造函数的QFile 对象参数进行初始化。dump 函数根据参数调用 dumpOne() 或 dumpOneDetailed() 将内容转储到标准输出、

struct CborDumper
{
    enum DumpOption { ShowCompact = 0x01, ShowWidthIndicators = 0x02, ShowAnnotated = 0x04 };
    Q_DECLARE_FLAGS(DumpOptions, DumpOption)

    CborDumper(QFile *f, DumpOptions opts_);
    QCborError dump();

private:
    void dumpOne(int nestingLevel);
    void dumpOneDetailed(int nestingLevel);

    void printByteArray(const QByteArray &ba);
    void printWidthIndicator(quint64 value, char space = '\0');
    void printStringWidthIndicator(quint64 value);

    QCborStreamReader reader;
    QByteArray data;
    QStack<quint8> byteArrayEncoding;
    qint64 offset = 0;
    DumpOptions opts;
};
dumpOne() 函数

打开QCborStreamReader::type() 可根据数据流中当前值的类型进行打印。如果值的类型是数组或映射,则对值的内容进行迭代,并以更高的缩进参数递归调用 dumpOne() 函数。如果类型是标签,则将其打印出来,并调用一次 dumpOne(),但不增加缩进参数。

dumpOneDetailed() 函数

该函数将输入的字节和解码后的内容转储到同一行。它使用 lambda 函数来打印字节和解码后的内容,其他结构与 dumpOne() 类似。

CborTagDescription

tagDescriptions 表格描述了可用的 CBOR 标记,它是由 iana.org 网站上的 XML 文件自动生成的。当dumpOneDetailed() 报告一个标记时,它会使用该表中的描述。

示例项目 @ code.qt.io

另请参阅 QCborStreamReaderQt 中的 CBOR 支持

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.