QJsonDocument::toJson with subobjects



  • Hi,

    I'm trying to output json data by using QJsonDocument and QJsonObject, but I have a problem with subobjects. The output always contains null for subojects. Below a small example:

    QVariantHash sub;
    sub.insert("id", 2);
    sub.insert("name", "world");
    
    QVariantHash root;
    root.insert("id", 1);
    root.insert("name", "hello");
    root.insert("sub", QJsonObject::fromVariantHash(sub));
    
    QString output = QJsonDocument(QJsonObject::fromVariantHash(root)).toJson(QJsonDocument::Compact);
    

    Output = {"id":1,"name":"hello","sub":null}

    What I am missing?
    Best regards,
    Jonathan



  • Hi,

    you try to add a QJsonObject to root.
    If you try to add the QVariantHash to root you will get a valid json

    QVariantHash sub;
    sub.insert("id", 2);
    sub.insert("name", "world");
    
    QVariantHash root;
    root.insert("id", 1);
    root.insert("name", "hello");
    root.insert("sub", sub);
    
    QString output = QJsonDocument(QJsonObject::fromVariantHash(root)).toJson(QJsonDocument::Compact);
    
    qDebug() << output; // prints "{\"id\":1,\"name\":\"hello\",\"sub\":{\"id\":2,\"name\":\"world\"}}" 
    

Log in to reply
 

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