解析和显示 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() 报告一个标签时,它会使用该表中的描述。
另请参阅 QCborStreamReader 以及Qt XML 中 CBOR 支持。
© 2026 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.