arraysjsonqtqjsonqjsonobject

How to generate JsonRpc request in qt?


I want to generate a qjsonstring in this format:

{"id": 1, "params":{"parameter1": 1, "parameter2": 2}}

But I don't know how to add parameter1 parameter2 to key params

This is my code:

QJsonObject *jsonObj = new QJsonObject(); 

jsonObj->insert("id",1);

jsonObj->insert("params",{"parameter1": 1, "parameter2": 2}); 

QJsonDocument *jsonDoc = new QJsonDocument(*jsonObj);  

QString jsonString = jsonDoc->toJson(QJsonDocument::Indented);

Can anyone help me?


Solution

  • According to the Json format, "params" refers to an object.

    Create the inner object first and add it to the "params" key

    // create the inner object
    QJsonObject paramsObj;
    paramsObj.insert("parameter1", 1);
    paramsObj.insert ("parameter2", 2);
    
    // create the main object
    QJsonObject jsonObj;
    jsonObj.insert("id", 1);
    // add the inner object
    jsonObj.insert("params", paramsObj);