QJson 的简单使用
可用于通讯的数据序列化与反序列化函数
#include <QJsonParseError> #include <QVariantMap> #include <QJsonObject> #include <QJsonArray> #include <QApplication> //序列化函数 QByteArray generateJson( const QVariantMap& map ) noexcept { QJsonObject object = QJsonObject::fromVariantMap( map ); QJsonDocument document( object ); return document.toJson( QJsonDocument::Compact ); } //反序列化函数 QJsonObject parserJson( const QString& data ) noexcept( false ) { QByteArray data_byte = data.toUtf8(); QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson( data_byte, &error ); if ( error.error == QJsonParseError::NoError ) { if ( doc.isObject() ) { return doc.object(); } else { throw QString( "Not a object" ); } } else { throw QString( "Not a Json : " ).append( error.errorString() ); } } int main( int argc, char* argv[] ) { QApplication a( argc, argv ); // 声明数据 QVariantMap task_list; QVariantMap task_info, task_info1; QVariantList agvStateList; //数据赋值 task_info["taskNum"] = 8; task_info["stationId"] = "001"; task_info1["taskNum"] = 6; task_info1["stationId"] = "002"; agvStateList.push_back( task_info ); agvStateList.push_back( task_info1 ); task_list.insert( "AgvNum", 2 ); task_list.insert( "Agvs", agvStateList ); //Json转化为16进制数据用于通讯 QByteArray data = generateJson( task_list ); char* content = data.data(); qint8* m_content = reinterpret_cast<qint8*>( content );
//QVariantMap解析Json数据
QVariantList list0 = task_list.value( "Agvs" ).toList();
QVariantMap zx1 = list0.toMap();
int task1 = zx1.value( "taskNum" ).toInt(); //16进制数据反序列化为Json数据解析 auto json_str = parserJson( reinterpret_cast<char*>( m_content ) ); int agv_num = json_str.value( "AgvNum" ).toInt(); QJsonArray zx = json_str.value( "Agvs" ).toArray(); QJsonObject zx1 = zx.at( 0 ).toObject(); int task1_num = zx1.value( "taskNum" ).toInt(); return a.exec(); }
QVariantListzzzzz=task_list.value("Agvs").toList();
QVariantMapmap=zzzzz[0].toMap();
inttask1=map.value("taskNum").toInt();