[Solved][QJsonDocument] Is QJsonDocument a thread safe?



  • i am using QJsonDocument::toJson(QJsonDocument::Compact),
    but it will get wrong json format when multi-thread enviroment,
    my jsonUtil method was below and only used local variable, what wrong about QJsonDcoument?
    Does someone can help me with some hint?

    const char* JsonUtils::toJson(const QJsonObject &obj) {
        QJsonDocument document(obj);
        QByteArray byteArray = document.toJson(QJsonDocument::Compact);
        char *json = byteArray.data();
        return json;
    }
    
    const char* JsonUtils::toJson(const QJsonArray &array) {
        QJsonDocument document(array);
        QByteArray byteArray = document.toJson(QJsonDocument::Compact);
        char *json = byteArray.data();
        return json;
    }

  • Moderators

    Hi,

    Your problem is not related to threads.

    Both your functions return invalid pointers. Your QByteArray is a local variable, so it is destroyed when the function returns. That means your char* pointer points to memory that has been deleted.

    Your functions should return QByteArray instead.



  • @JKSH

    wow, this was a big mistake, too stupid to see that

    thanks for your reply, i would try return object instead.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.