相关文章推荐
叛逆的洋葱  ·  3.2.4 ES6 数组 | 菜鸟教程·  4 月前    · 
善良的芹菜  ·  reactjs - React ...·  1 年前    · 
愤怒的豆芽  ·  vue.js - Vuejs: ...·  1 年前    · 
首发于 编程456

Qt Socket Server 收发JSON

之前文章写过Linux C Socket 收发Json数据,最近用Qt Server实现了一遍。给我自己的感觉就是cJSON接口与Qt封装的一些接口是共通的:Qt 封装了QJsonObject来对Json对象操作,如增删改查;封装了QJsonDocument来进行一些序列化与反序列化的操作(可能不准确)。

重要消息:虽然明天是端午节,但是还是要去公司学习。。。

后续可能会在公众号中写一点儿理财相关的知识,待定中......


程序中用到了Qt 的Socket Server,但主要介绍下Qt中如何操作Json数据,将接收到的字节流转换为Json对象,又如何将Json对象转换为字节流。


一、程序介绍

  1. Json 操作相关函数

为了与C语言写的对比,同样写了3个函数:

Qt :

    int ParseRecvJsonData(const  QByteArray &recvdata, int *outLogLevel);
    int WriteLogLevelToFileJson(const QString &filePathName, const int logLevel);
    int CreateRespondInfoJson(QByteArray *respondInfoJson, const  QByteArray &recvJsonData,const int writeFileRet);

C:

int ParseRecvJsonData(const char * recvdata, int *outLogLevel);
int WriteLogLevelToFileJson(const char *filePathName, int logLevel);
int CreateRespondInfoJson(char *respondInfoJson, const char* recvJsonData,const int writeFileRet);


解析Json字节流为Json对象,提取所需信息

将所需信息组装成Json对象写入配置文件

将字节流转换为Json对象并添加数据,组装成响应信息


2. Qt 中对Json操作的具体实现

直接加注释进行说明

int TcpServerRecvImage::CreateRespondInfoJson(QByteArray *respondInfoJson,
               const QByteArray &recvJsonData, const int writeFileRet)
//使用QJsonDocument判断字节流能否转成Json对象
    QJsonParseError jsonError;
    QJsonDocument jsonRecvData(QJsonDocument::fromJson(recvJsonData, &jsonError));
    if(jsonError.error != QJsonParseError::NoError)
        qDebug() << "parse json error!";
        return -1;
//通过QsonDocument将字节流转为Json对象
    QJsonObject rootObject = jsonRecvData.object();
//向Json对象中追加数据
    rootObject.insert("Result","FAIL");
    if(0 == writeFileRet)
//修改对应数据;可以思考下是如何实现修改前与修改后数据所占空间不同
        rootObject["Result"] = "SUCCESS";
//将Json对象转换为字节流
    QJsonDocument documentJson;
    documentJson.setObject(rootObject);
    QByteArray bytearrayJson = documentJson.toJson();
    respondInfoJson->clear();
    respondInfoJson->append(bytearrayJson);
    return 0;
}


int TcpServerRecvImage::WriteLogLevelToFileJson(const QString &filePathName, const int logLevel)
//Qt文件操作
    QFile f(filePathName);
    if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
        qDebug() << "Open failed.";
        return -1;
    // create JSON Object
    QJsonObject logLevelJson;
    logLevelJson.insert("logLevel",QString::number(logLevel));
    QJsonDocument documentJson;
    documentJson.setObject(logLevelJson);
    QByteArray bytearrayJson = documentJson.toJson();
//使用QTextStream,简化文件操作
    QTextStream txtWrite(&f);