Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

JSON encoding for a POST request



  • Hi all,

    I'm facing a problem with acute characters using Qt.

    I have to post a JSON to an API so I'm using qJsonDocument class in order to write my JSON.

    If I qDebug() my qJsonDocument, i get this:

    createProyect: QJsonDocument({"data":{"name":"Pruebá de acentós","workspace":"5168224827749"}})

    But when I call .toJson() (Acording to documentation, Converts the QJsonDocument to a UTF-8 encoded JSON document) in order to perform a POST, qDebug() gives me this:

    createProyect: qjsondoc.toJson(): "{\n "data": {\n "name": "Prueb\xC3\xA1 de acent\xC3\xB3s",\n "workspace": "5168224827749"\n }\n}\n"

    My acutes turns like "\xC3\xA1" and the server sends me back a server error...

    Any idea why?

    Regards,

    Dani.



  • @Daniziz said in JSON encoding for a POST rquest:

    My acutes turns like "\xC3\xA1"

    That's correct, it's the hex codes for the letter's unicode point: http://www.fileformat.info/info/unicode/char/e1/index.htm

    and the server sends me back a server error

    How do you send your string to the server?



  • Hi @VRonin

    I just call QNetworkAccessManager POST this way:

    QByteArray jsonUTF8 = jsonDoc.toJson();
    qDebug() << "createTask: POSTING..." << jsonUTF8;
    reply = restclient->post(request, jsonUTF8);
    

    Im starting to think that maybe I must specify enconding in headers petition (But I havent figured it out yet), this is what I do:

    QString header = "Bearer " + access_token;
    request.setRawHeader(QByteArray("Authorization"), QByteArray(header.toLatin1().data()));
    request.setHeader(request.ContentTypeHeader,"Content-Type: application/json");
    

    Thanks for yout help.

    Regards,

    Dani.



  • request.setHeader(QNetworkRequest::ContentTypeHeader,QStringLiteral("Content-Type: application/json; charset=utf-8"));



  • @VRonin OMG, that simple... Thank you very much, it worked!

    I was doing it this way without success...

    request.setRawHeader( "charset", "utf-8" );
    

    Thank you very much!

    Regards,

    Dani.


Log in to reply